首页 > 解决方案 > .htaccess(强制 https 和无 www)不起作用

问题描述

您好,感谢您查看我的问题。我坚持让我的 .htaccess 文件工作。我已经在 stackoverflow 论坛上尝试了很多推荐的东西,但它们似乎都不适合我。我的 .htaccess 位于我的 apache 服务器根目录中,似乎没有做任何事情。我应该提到我的 .htaccess 文件已经被 XenForo 修改过。

这是我当前的 .htaccess 文件:

#   Mod_security can interfere with uploading of content such as attachments. If you
#   cannot attach files, remove the "#" from the lines below.
#<IfModule mod_security.c>
#   SecFilterEngine Off
#   SecFilterScanPOST Off
#</IfModule>

ErrorDocument 401 default
ErrorDocument 403 default
ErrorDocument 404 default
ErrorDocument 405 default
ErrorDocument 406 default
ErrorDocument 500 default
ErrorDocument 501 default
ErrorDocument 503 default

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
    RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]

    #   If you are having problems with the rewrite rules, remove the "#" from the
    #   line that begins "RewriteBase" below. You will also have to change the path
    #   of the rewrite to reflect the path to your XenForo installation.
    #RewriteBase /xenforo

    #   This line may be needed to workaround HTTP Basic auth issues when using PHP as a CGI.
    #RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^(data/|js/|styles/|install/|favicon\.ico|crossdomain\.xml|robots\.txt) - [NC,L]
    RewriteRule ^.*$ index.php [NC,L]
</IfModule>

我还尝试放置这些行的不同版本:

    RewriteEngine On

    RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
    RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]

在文件的最顶部,但这也不起作用。

我的目标是始终保持网址非 www 并强制使用 https。提前感谢您的帮助。

标签: .htaccesssslhttps

解决方案


这会将 www 重定向到非 www,将非 https 重定向到 https。

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

推荐阅读