So historically, the domains of sites are called with or without the www prefix.
There are several views on how a domain should truly be called, progressive humanity believes that without www -
nowww.ru , many Western experts believe the opposite.
However, this is not about this, but about how to organize a constant round-trip redirect in our favorite web servers.
')
First of all, it must be said that the redirect should be permanent, i.e. give the response code 301 Moved Permanently so that browsers do not remember the url from which the redirect was made.
The general principle is:
* we describe the server with the name of the server from which we redirect
* specify the directive for redirect
Apache 2.2, 2.0, 1.3,
RedirectMatch from mod_alias , the
same can be done with mod_rewrite :
<VirtualHost *:80> ServerName example.com:80 RedirectMatch permanent (.*) http://www.example.com$1 </VirtualHost>
Nginx,
rewrite from http_rewrite_module :
server { server_name example.com; rewrite ^(.*)$ http://www.example.com$1 permanent; }
In order not to specify this rule for each domain, you can use a negative regular expression:
server { server_name ~^(?! www\.); rewrite ^ http://www.$host$request_uri permanent; }
At the same time, clearly described sites without www will no longer be included here - regexs
server_name is used as last resort.
The author of the decision is Igor Sysoev.
It would be great if we list the ways of organizing permanent redirects for other popular web servers.
UPD: added a note on the general redirect for nginx