htaccess更改域名,前缀“ www。”除外。

时间:2019-03-08 07:47:47

标签: apache .htaccess url-rewriting

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

  1. 总是在域名前添加“ https://”,或将“ http://”更改为“ https://”;
  2. 添加前缀“ www。”。如果未使用前缀,则在域名之前(“ https://”之后),并且请勿更改其他前缀(例如“ mobile”。)。

因此,“ example.com”或“ http://example.com”将变为:“ https://www.example.com”, “ ”或“ http://mobile.example.com”将变为“ https://mobile.example.com”。

2 个答案:

答案 0 :(得分:0)

您的.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>

答案 1 :(得分:0)

我使用此简单的 .htaccess 文件更改 http-> https 并添加 www (如果未设置)

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [nc]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}