简体   繁体   English

.htaccess-删除www,强制使用https,删除php并删除斜杠

[英].htaccess - Remove www, force https, remove php and remove trailing slash

I am trying to archieve the following with least amount of redirects; 我正在尝试以最少的重定向量归档以下内容;

  • Remove WWW 删除WWW
  • Force HTTPS 强制HTTPS
  • Remove php extension 删除PHP扩展
  • Remove end trailing slash 删除尾随斜杠

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]

Current behaviour: 当前行为:

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

(works with 4 redirects) (适用于4个重定向)

OR 要么

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

(works with 4 redirects) (适用于4个重定向)

Does anyone have any suggestions how to make this work with fewest possible redirects? 有没有人对如何使重定向最少的建议有任何建议?

It doesn't hurt to just always rewrite to https and lose the www in one step. 只总是一步步重写为https并丢失www并没有什么害处。 Trailing slash is unchanged, but lost a line on removing php-extenstion by inverting the Cond. 尾部的斜杠保持不变,但是在通过反转条件来删除php-extensions时丢失了一行。

# 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]

If you also need handling for files that were requested as file/ without .php , you should stay with your code for the final part: 如果您还需要处理作为file/而不使用.php ,则应保留最后一部分的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM