RewriteCond %{SERVER_NAME} syntax

13,797

To match against both www and non-www host in a single line, you can use the following regex pattern :

^(www\.)?example\.com$

This matches www.example.com or example.com .

To force ssl www, you can use this :

RewriteEngine on

RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule (.*) https://www.example.com/$1 [L,R,NE]
Share:
13,797
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to understand the following syntax (see usage context below):

    RewriteCond %{SERVER_NAME} ^example\.com$
    

    I have the above (with real domain name in place of example) in my .htaccess file. I would like to force it to be www.example.com.

    The website has SSL and the following SSL Coding was added by the SSL Install process at GoDaddy. So I trying to work with both this coding, and changing to force to www with the SSL.

    # BEGIN GD-SSL
    <IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_USER_AGENT} ^(.+)$
    RewriteCond %{SERVER_NAME} ^example\.com$
    RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
    Header add Strict-Transport-Security "max-age=300"
    </IfModule>
    # END GD-SSL
    

    I tried to add mod rewrite rules to force www and they are not working. I think the problem resides in the RewriteCond %{SERVER_NAME} ^example.com$ which is not resolving to the "www". I thought I might need to add the www. to this, however, I am not sure if this is correct.
    Would this be the solution to change the ssl to force WWW in the URL? Or do I need to do something else entirely?

     RewriteCond %{SERVER_NAME} ^www\.^example\.com$
    

    Any help would be greatly appreciated. Thank you.

    Becky