How can I match www and non-www in rewritecond?

I have a rewritemap that has a list of domains to redirect. Currently I have to list www.foo.com and foo.com on the rewrite card. I was wondering if there is a way to check re-entry for www and non-www on the same line.

# Rewrite Map foo.com file.php www.foo.com file.php # modrewrite RewriteCond ${domainmappings:%{HTTP_HOST}} ^(.+)$ [NC] RewriteCond %1 !^NOTFOUND$ RewriteRule ^.*$ www.domain.com/%1 [L,R=301] 

I tried doing things like (www.)% {HTTP_HOST} or ^ (www.)% {HTTP_HOST} but no luck.

+8
regex apache mod-rewrite rewritemap
source share
4 answers

This should do it:

 RewriteCond %{HTTP_HOST} ^(www\.)?(.+) RewriteCond ${domainmappings:%2} ^(.+)$ [NC] RewriteRule ^ /%1 [L,R=301] 

The first RewriteCond will remove the optional www. prefix www. . The rest is then used as a parameter for the rewriting card in the second RewriteCond .

The overwrite map of a plain text file returns an empty string if no match is found:

If the key is found, the map-function construct is replaced with SubstValue. If the key is not found, it is replaced by DefaultValue or an empty string if the value of DefaultValue is not specified.

So, if the second condition is met (note ^(.+)$ ), A match is found, and %1 will contain SubstValue (in this case file.php ).

+15
source share

From the message here

http://www.eukhost.com/forums/f15/simple-rewriterule-set-redirect-domain-6570/

 RewriteEngine on RewriteCond %{HTTP_HOST} ^xyz.com$ [OR] RewriteCond %{HTTP_HOST} ^www.xyz.com$ RewriteRule ^(.*)$ http://www.xyz.com/test//$1 [R=301,L] 
+5
source share

You can try to do www. optional with the following parameters:

 # Rewrite Map www.foo.com file.php # modrewrite # redirect to www domain always RewriteCond %{HTTP_HOST} ^([^.]+\.[^.]+)$ RewriteRule (.*) http://www\.%1/$1 [L,R=301,QSA) # redirect following the map RewriteCond ${domainmappings:%{HTTP_HOST}} ^(.+)$ [NC] RewriteCond %1 !^NOTFOUND$ RewriteRule ^.*$ www.domain.com/%1 [L,R=301] 

This will redirect anything.anything to www.anything.anything , and then apply your rule to the next request. Not too knowledgeable about rewriting cards, so no guarantees.

0
source share
 RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^domain.com$ [OR] RewriteCond %{HTTP_HOST} ^www.domain.com$ RewriteRule ^ https://www.domain.com%{REQUEST_URI} [R=301,L] 
0
source share

Source: https://habr.com/ru/post/650563/


All Articles