【问题标题】:Remove "WWW" from "{HTTP_HOST}" in htaccess rules从 htaccess 规则中的“{HTTP_HOST}”中删除“WWW”
【发布时间】:2016-08-26 23:28:51
【问题描述】:

我有 3 个网址并且有 ssl 认证

1) www.example.com

2) myexample.com

3) otherexample.com

我需要将以上三个网址都重定向到 https 安全网址 例如: 当用户打开上面的任何一个 url 时,它应该重定向到 https url。

=> when user open www.example.com OR example.com >>> it should redirect to https://www.example.com
=> when user open www.myexample.com OR myexample.com OR https://www.myexample.com >>> it should redirect to https://myexample.com
=> when user open www.otherexample.com OR otherexample.com OR https://www.otherexample.com >>> it should redirect to https://otherexample.com

注意:我有 www.example.com、myexample.com(non-www)、otherexample.com(non-www) 的 ssl 证书

我需要帮助来解决我的问题。我也想动态设置规则,所以将来如果我有更多的 url,就不会编辑 .htaccess 文件。 (如果可以从下面的 {HTTP_HOST} 设置规则中删除“www”,这样对我有好处)

我在 htaccess 中设置了一些规则,但它对我不起作用。

RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}$1 [R=301,L]

#rule for myexample.com
RewriteEngine On
RewriteCond %{HTTP_HOST}  ^www.example.com [nocase]
RewriteRule ^(.*)         https://example.com/$1 [last,redirect=301]

#rule for otherexample.com
RewriteEngine On
RewriteCond %{HTTP_HOST}  ^www.otherexample.com [nocase]
RewriteRule ^(.*)         https://otherexample.com/$1 [last,redirect=301]

【问题讨论】:

    标签: php apache .htaccess redirect ssl


    【解决方案1】:

    我希望它对你有用。

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    

    【讨论】:

    • 是的,我已经设置了这个 url,但是对于其他 url 它将不起作用。当用户打开 www.myexample.com 时,它会重定向到myexample.com,但 ssl 证书会给出异常。这是我要解决的主要问题。 :)
    • 此链接将有助于您获取动态域或子域。stackoverflow.com/questions/19427256/…
    【解决方案2】:

    尝试以下方法:

    RewriteEngine on
    
    #redirect any other domain that is not "www.example.com" to "https://"
    RewriteCond %{HTTPS} off 
    RewriteCond %{HTTP_HOST} (?:www\.)?((?!example\.com).+)$
    RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
    #redirect  "www.example.com" to "https://www"
    RewriteCond %{HTTPS} off 
    RewriteCond %{HTTP_HOST} (?:www\.)?((example\.com).+)$
    RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
    

    【讨论】:

    • 您的解决方案对我有用,但它只是静态的。我想让它动态化。我不想静态地写每个 url。
    • 抱歉,动态是什么意思?
    • 当用户打开 www.myexample.com 时,它会重定向到myexample.com,但 ssl 证书会给出异常。这是我要解决的主要问题。所以我需要像如果我打开 www.myexample.com 或 www.otherexample.com 这样的解决方案,它将重定向到 myexample.com,https://otherexample.com 相应
    • 如果上面的代码对你有用,那么这个链接对你创建动态域很有帮助。 stackoverflow.com/questions/19427256/…
    • @MousamiRoul : 你能帮我理解这行 RewriteCond %{HTTP_HOST} ^(?:www\.)?((?!www\.)[^.]+\.) ?([^/.]+\.[^/.]+)/?([^/]+)?$ [NC]
    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 2016-10-01
    • 2017-07-22
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多