URL重定向 - 更改文件夹,用短划线替换下划线并删除html扩展名

时间:2016-06-22 15:33:08

标签: .htaccess

我有一个旧网站,我有下划线和html扩展名,我想以下列方式重定向

http://example.com/news/this_is_a_test.html -> http://example.com/post/this-is-a-test

http://example.com/portfolio/another_test.html -> http://example.com/project/another-test

除了新闻和投资组合之外还有其他文件夹,显然网址的最后一段有不明数量的下划线。

这是我目前正在使用的.htaccess(基于我原来的问题htaccess file to remove folder, and replace underscores with dashes)。它适用于新闻示例,但如果我尝试投资组合则会中断。

知道我哪里出错了?

RewriteEngine on

# redirect "/news_bar" to "/foo_bar"
RewriteRule ^news/(.+)$ /$1 [L,R]
#2 replace underscore with hypens
RewriteRule (.*)_(.*) $1-$2 [N,E=uscores:yes]
RewriteCond %{ENV:uscores} yes
RewriteRule ^(.+)$ /post/$1 [L,R]

RewriteRule ^portfolio/(.+)$ /$1 [L,R]
RewriteRule (.*)_(.*) $1-$2 [N,E=uscores:yes]
RewriteCond %{ENV:uscores} yes
RewriteRule ^(.+)$ /project/$1 [L,R]

# remove .html from end of url

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

非常感谢!

1 个答案:

答案 0 :(得分:1)

之前我有一个solution,但它在我当前的设置(Apache崩溃)上打破了,所以我推荐它适合你的情况是不明智的。 (这可能是我的设置问题,但我更愿意为您提供更直接的路线。)

此解决方案涉及将相关请求发送到将执行必要替换的PHP文件,并仅重定向一次。请注意,您当前的实现将向浏览器发送多个重定向指令。从用户体验的角度来看,这不仅是坏的,而且也来自SEO。

要实施解决方案,首先将.htaccess指令替换为:

RewriteEngine On

# Rewrite news and portfolio links to redirect.php
RewriteRule ^(news|portfolio)/(.+).html /redirect.php [L]

然后,在与redirect.php文件相同的目录中创建一个.htaccess文件(在本例中为您的文档根目录),并使用这个简单的替换方法和重定向指令填充它:

<?php

$path = $_SERVER['REQUEST_URI'];

# Perform the necessary replacements. The first array contains
# what we're searching for, bit by bit, and the second array
# contains the relevant replacements.
$path = str_replace(
    ['_', '/news/', '/portfolio/', '.html'],
    ['-', '/post/', '/project/',   ''],
$path);

# Now, simply redirect to the new path.
# Change 302 to 301 use a "Moved Permanently" header,
# resulting in browsers and search engines caching
# the redirect.
header("Location: $path", true, 302);