.htaccess - 删除www,强制https,删除php并删除尾部斜杠

时间:2017-04-05 22:31:49

标签: php apache .htaccess redirect mod-rewrite

我试图用最少量的重定向来实现以下目标;

  • 删除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次重定向)

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

1 个答案:

答案 0 :(得分:3)

总是重写为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]