首页 > 解决方案 > htaccess 更改域名,但前缀“www”除外。

问题描述

我想通过 htaccess 为我的域“example.com”实现以下目标:

  1. 始终在域名前添加“https://”或将“http://”更改为“https://”;
  2. 添加前缀“www。” 如果没有使用前缀,则在域名之前(“https://”之后),并且不要更改其他前缀(如“mobile.”)。

所以“example.com”或“http://example.com”将变为:“https://www.example.com”和“mobile.example.com”或“http://mobile.example.com” ' 将变为 'https://mobile.example.com'。

标签: apache.htaccessurl-rewriting

解决方案


你的.htaccess文件应该是:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Start with www
    #RewriteCond %{HTTP_HOST} !^www\. [NC]
    #RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    #RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

    # force http to https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]


    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

</IfModule>

推荐阅读