I want to redirect all http requests to https, and all www requests to non-www

帅比萌擦擦* 提交于 2020-01-06 01:57:13

问题


Here is my current .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
</IfModule>

I want to redirect all http requests to https, and all www requests to non-www, and all file requests to index.php

For example:

http://www.example.com to https://example.com

https://www.example.com to https://example.com

http://example.com/file.php to https://example.com/index.php

Everything seems to be working except the www part.. Any help please?


回答1:


You can add an additional rule dealing with the www part

RewriteCond %{HTTP_HOST} ^www\.(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [L,R]

The RewriteCond captures everything after the www. and uses that in the RewriteRule as %1.

When everything works as you expect, you can change R to R=301.

Never test with 301 enabled, see this answer Tips for debugging .htaccess rewrite rules for details.




回答2:


http://www.example.com to https://example.com
https://www.example.com to https://example.com
http://example.com/file.php to https://example.com/index.php

Maybe this will work:

RewriteEngine On

# Remove www from https requests. 
# Next 3 lines must be placed in one .htaccess file at SSL root folder, 
# if different from non-ssl.
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST}  ^www\.(.+) [NC]
RewriteRule ^(.*) https://%1/$1 [R=301,L]

# Redirect all http to https
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (?:www\.)?(.+)  [NC]
RewriteRule ^(.*) https://%1/$1     [R=301,L]

If it doesn't work, try replacing

RewriteCond %{HTTPS} off or on with

RewriteCond %{HTTP:X-Forwarded-SSL} off or on



来源:https://stackoverflow.com/questions/16204124/i-want-to-redirect-all-http-requests-to-https-and-all-www-requests-to-non-www

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!