开发者

.htaccess - how to force "www." in a generic way?

开发者 https://www.devze.com 2023-02-09 02:38 出处:网络
This will change domain.example to www.domain.example: # Force the "www." RewriteCond %{HTTP_HOST} !^www\\.domain\\.example$ [NC]

This will change domain.example to www.domain.example:

# Force the "www."
RewriteCond %{HTTP_HOST} !^www\.domain\.example$ [NC]
RewriteRule ^(.*)$ `http://www.domain.example/$1` [R=301,L]

How do I replace the "domain开发者_StackOverflow中文版" part so that this works on any domain?


I would use this rule:

RewriteEngine On
RewriteCond %{HTTP_HOST} !=""
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The first condition checks whether the Host value is not empty (in case of HTTP/1.0); the second checks whether the the Host value does not begin with www.; the third checks for HTTPS (%{HTTPS} is either on or off, so %{HTTPS}s is either ons or offs and in case of ons the s is matched). The substitution part of RewriteRule then just merges the information parts to a full URL.


This will do it:

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


If you want to redirect all non-www requests to your site to the www version, all you need to do is add the following code to your .htaccess file:

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


This won't work with subdomains.

domain.example correctly gets redirected to www.domain.example

but

images.domain.example gets redirected to www.images.domain.example

Instead of checking if the subdomain is "not www", check if there are two dots:

RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ HTTP%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


The following should prefix 'www' to any request that doesn't have one, and redirect the edited request to the new URI.

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


RewriteEngine On

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

This redirects example.com to www.example.com excluding subdomains.


This is an older question, and there are many different ways to do this. The most complete answer, IMHO, is found here: https://gist.github.com/vielhuber/f2c6bdd1ed9024023fe4 . (Pasting and formatting the code here didn't work for me)


this worked like magic for me

RewriteCond %{HTTP_HOST} ^sitename.example [NC]
RewriteRule ^(.*)$ https://www.sitename.example/$1 [L,R=301,NC]
0

精彩评论

暂无评论...
验证码 换一张
取 消