.htaccess-删除www,强制使用https,删除php并删除斜杠
问题描述:
我正在尝试以最少的重定向量归档以下内容;
I am trying to archieve the following with least amount of redirects;
- 删除WWW
- 强制HTTPS
- 删除php扩展名
- 删除结尾的斜杠
到目前为止,我正在工作:
What i have so far and is working:
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个重定向)
有人对如何使重定向最少的建议有任何建议吗?
Does anyone have any suggestions how to make this work with fewest possible redirects?
答
仅一步步始终重写为https并丢失www并没有什么害处.尾部的斜杠没有改变,但是在通过反转条件来删除php-extensions上失去了一行.
It doesn't hurt to just always rewrite to https and lose the www in one step. Trailing slash is unchanged, but lost a line on removing php-extenstion by inverting the Cond.
# 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]
如果您还需要处理不带.php
的file/
请求的文件,则应保留最后一部分的代码:
If you also need handling for files that were requested as file/
without .php
, you should stay with your code for the final part:
RewriteRule ^(.+)\.php$ /$1 [NC,L,R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)/?$ /$1.php [END]