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
?
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.The above redirects any request of the form
example.com/<anything>
tohttp://www.example.com/<anything>
. TheREQUEST_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.
NB:
example.com
andhttp://example.com
are the same - the browser simply hides the protocol (and defaults to HTTP for most users). The same forwww.example.com
andhttp://www.example.com
.UPDATE:
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 setAllowOverride
(the default is `None). For example: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):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: