.htaccess-删除www,强制使用https,删除php并删除斜杠 [英] .htaccess - Remove www, force https, remove php and remove trailing slash

查看:92
本文介绍了.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]

如果您还需要处理不带.phpfile/请求的文件,则应保留最后一部分的代码:

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]

这篇关于.htaccess-删除www,强制使用https,删除php并删除斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆