1

I have a website www.example.com running on Apache.

Maybe someone got to me via example.com, or www.example.com, or http://example.com, or even http://www.example.com.

Can I use the rewrite rules in .htaccess so that however they get to example.com, the URL is fully fleshed out to http://www.example.com?

1 Answers1

0

Assuming Apache is already accepting requests to both the www subdomain and the domain apex (ie. example.com) then you can canonicalize the hostname to www using something like the following using mod_rewrite near the top of your .htaccess file in the document root.

RewriteEngine On

RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The above redirects any request of the form example.com/<anything> to http://www.example.com/<anything>. The REQUEST_URI server variable contains the full URL-path, including the slash prefix. Any query string that might be on the original request is passed through unchanged.

Test first with a 302 (temporary) redirect to avoid potential caching issues.

Maybe someone got to me via example.com, or www.example.com, or http://example.com, or even http://www.example.com.

NB: example.com and http://example.com are the same - the browser simply hides the protocol (and defaults to HTTP for most users). The same for www.example.com and http://www.example.com.


UPDATE:

when I just tried this out, the browser URL remains example.com

If you haven't done so already, you need to enable .htaccess overrides in the server config, otherwise the .htaccess file will simply be ignored.

In the appropriate <Directory> container inside the <VirtualHost> (or main server config) you need to set AllowOverride (the default is `None). For example:

<Directory /path/to/document-root>
    Options +FollowSymLinks
    Require all granted
# Enable .htaccess overrides
AllowOverride All

</Directory>

AND, if you haven't already, you need to enable mod_rewrite:

Debugging .htaccess

You can increase the LogLevel (Apache 2.4+) in the server config to output debug information to the server's error log. For example, in the respective <VirtualHost> container (or main server config):

LogLevel debug

This sets the "log level" for all modules. The default is LogLevel warn. To target just a specific module, such as mod_rewrite (used above) then you can specify just that module. eg. LogLevel rewrite:debug.

Reference:

MrWhite
  • 298