htaccess从带有多个正斜杠的URL中删除.php扩展名

时间:2016-04-15 04:39:35

标签: php .htaccess redirect mod-rewrite

我需要301将以.php结尾的所有网址重定向到非扩展版本。但重写规则需要与下面的现有规则一起使用。

# ==== REWRITE URLS ====
RewriteEngine On
# pass through root
RewriteRule ^(index\.php|Sitemap\.xml)?$ - [L]
# no more / so add extension
RewriteCond $1 !/
RewriteCond $1 !\.php$
RewriteCond ${REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /$1.php [L]
RewriteCond %{REQUEST_URI} !\.php$
RewriteRule ^(_assets|_css|_fonts|_includes|_scripts)($|/) - [L] #exclude these folders using the 'last: L' flag
RewriteRule ^(.*)/(.*)$ /$1-$2 [L]

这是此问题here的扩展。

所以期望的结果是:

domain.com/region/brand/more-content-here.php

永久重定向到:

domain.com/region/brand/more-content-here

但是获取实际文件:

domain.com/region-brand-more-content-here.php

尝试了一些不同的想法,但他们似乎没有使用现有规则,而htaccess不是我的力量。还需要它是querystring友好。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

要删除.php扩展名,您可以使用:

RewriteEngine on

#1)Permanently redirect "foo.php" to "/foo"#
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
 RewriteRule ^ /%1 [NE,L,R=301]
#2)Rewrite "/foo" to "/foo.php"#
#this will internally redirect file to file.php#
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

答案 1 :(得分:1)

工作代码:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f