skip to Main Content

I want a rather simple feature, I want my website to work when someone puts a www. before my domain name. My preference is to redirect all http://www. requests to http:// without anything complicated.

I have tried two methods to this and neither works desirably. The first option was to simply add this following rewrite engine command in the site’s .htaccess (which, for the record, I confirmed was working)

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

I tried numerous variations of this code, and none of them do a thing. Even after resetting my browser cache, accessing through Tor, if I enter my website with the www. prefix then it simply doesn’t load and Firefox gives me a “server not found” error.

The second thing that I have tried is to remove all rewrite codes and simply add the DNS record A, with the host www that points to my IP address. After waiting a little bit, the website was now working! However, it was incredibly inconsistent, because if I were to access www.example.com then it would remove the www., but if I went to www.example.com/page.html then it wouldn’t remove it (but it’d still work). Another weird issue is that if I typed www.example.com/folder/page, it’d send me to www.example.comfolder/page.

Does anyone have any advice on what should I do or what I could be doing wrong?

2

Answers


  1. This should work.

    RewriteEngine On 
    RewriteCond %{HTTP_HOST} !^example.com 
    RewriteRule (.*) http://example.com/$1 [R=301,L] 
    
    Login or Signup to reply.
  2. (This is not necessarily an answer, but my reputation is not yet sufficient to post a comment.)

    The previous comment looks like it should do the job, so something unexpected is going on with the rewrite.

    You might try enabling rewrite logging at a low level to see what is going on with the rewrite rule. Increase logging level by one level if the issue is not revealed. Note that logging mod_rewrite actions can produce really big logs, so it is prudent to try this on a testbed or a relatively idle host.

    # Enable mod_rewrite
    RewriteEngine On
    
    # RewriteLogLevel: Controls verbosity of mod_rewrite log
    #                  0=off, 9=max
    RewriteLogLevel 2
    

    As a side note and imo, I would do this in the config file and not in an .htaccess file because this rule should be applied site-wide on this host/vhost. This also makes it impossible for Apache to avoid executing the rewrite by ignoring the .htaccess file.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search