2017-04-05 221 views
0

我想用最少量的重定向来实现以下目标;.htaccess - 删除www,强制https,删除php并删除尾部斜杠

  • 删除WWW
  • 力HTTPS
  • 删除PHP扩展
  • 删除结束斜线

我有什么事这么远,是工作:

RewriteEngine On 

# REMOVE WWW 
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] 
RewriteRule ^(.*)$ http://%1/$1 [R=301,L] 

# FORCE HTTPS 
RewriteCond %{HTTP:X-Forwarded-Proto} !https 
RewriteRule^https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

# REMOVE TRAILING SLASH 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)/$ /$1 [L,R=301] 

# REMOVE PHP EXTENSION 
RewriteRule ^(.+)\.php$ /$1 [NC,L,R=301] 
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.+)/?$ /$1.php [END] 

当前行为:

http://www.example.com/functions.php -> https://example.com/functions 

(含4个重定向作品)

OR

http://www.example.com/functions/ -> https://example.com/functions 

(含4个重定向作品)

没有人有任何建议,如何使尽可能少的重定向这项工作?

+0

[获取.htaccess文件的可能的复制工作中子文件夹](http://stackoverflow.com/questions/27642401/getting-htaccess-file-to-work-in-subfolders) –

回答

1

它不会伤害到只是总是重写为https并一步失去www。跟踪斜杠不变,但通过反转Cond消除了php-extenstion的一行。

# REMOVE WWW & FORCE HTTPS 
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR] 
RewriteCond %{https} off 
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L] 

# REMOVE TRAILING SLASH 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)/$ /$1 [L,R=301] 

# REMOVE PHP EXTENSION if there's no file with this name 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.+)\.php$ /$1 [NC,L,R=301] 

如果您还需要处理的请求被作为不file/.php文件,你应该留你到最后的部分代码:

RewriteRule ^(.+)\.php$ /$1 [NC,L,R=301] 
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.+)/?$ /$1.php [END] 
+0

第一部分结合了removeral的www和force https作品。虽然删除extionion的最后部分不起作用。但现在还好些,我只有3个重定向。 – puntable

+0

当要求的文件实际上不存在时,你想删除'.php',对吗?你有两条规则,首先,如果请求的URI以'something.php'结尾,你重写为/ something。其次,当一个文件名“.php”被请求并且实际存在时,URI的最后部分被“.php”取得并扩展。所以如果文件不存在,简短的版本只能删除'.php'。我的规则确实如此:/ RewriteCond被满足,如果请求的文件不存在,然后它剥离'.php'。 –

+0

只有第二部分,如果有名为'%{REQUEST_FILENAME} .php'的文件,添加'.php'不会被处理,因为它不是您原始问题的一部分,但是如果这也应该完成,那么你应该留在你的最后一个规则集。相应地编辑我的答案 –