开发者

Using htaccess to redirect requests from non-www to www (but with a twist)

开发者 https://www.devze.com 2022-12-12 12:58 出处:网络
I\'m currently using htaccess to force all requests to use www. So: RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]

I'm currently using htaccess to force all requests to use www. So:

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
Re开发者_运维问答writeRule ^(.*)$ http://www.example.com/$1 [L,R=301]

to redirect example.com/page to www.example.com/page.

However, this htaccess file is being used by several international versions of example.com. What code do I want that can also do the following:

example.de/page -> www.example.de/page and example.co.uk/page -> www.example.co.uk/page etc.

Potentially, there could be dozens of versions of example.com, so I'm looking to avoid having to remember to edit htaccess every time we add a new country.


You can use server variables in your substition, so this should be doable with

RewriteRule ^(.*)$ http://www.${HTTP_HOST}/$1 [L,R=301]


Right: think I've actually got it cracked. (Or at least it looks like it works):

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

seems to do the trick.


Test if the current host name does not begin with www. and add it if missing:

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

精彩评论

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