The apache server realizes the jump without www to the domain name with www

user:visitors Date:2022-04-17 18:40:01997

When we browse the web, we will find that the website address of many web pages displayed in the browser address bar, the second-level domain name with www prefix and the first-level domain name without www can be accessed directly, but when we enter the address without www When prefixing the URL, the browser will automatically jump to the second-level domain name with www. How is this achieved?

When apache2.4 is used as a web server, generally we will bind two domain names for the site in the configuration file.


The configuration is as follows:

<VirtualHost *:80>

DocumentRoot "C:/www"

ServerName www.xxxxx.xxx

ServerAlias xxxxx.xxx

<Directory "C:/www">

Options FollowSymLinks Includes

AllowOverride All

Require all granted

</Directory>

</VirtualHost>


So after this setting, when we visit the site configured by ourselves, both with and without www can be accessed, but there is no jump, so how to set it?

First, we can open the Mod_Rewrite rewrite rule module, which can analyze regular expressions to rewrite url requests.

We only need to modify the httpd.conf configuration file in the conf directory of the apache server.

Remove the # in front of LoadModule rewrite_module modules/mod_rewrite.so, save and restart the server.

Then use notepad to create a new blank text, then save as save type as all files, set the name to .htaccess, it should be noted that it does not have the name of the file, only the suffix .htaccess.


Then right-click to open with and select Notepad to add the following code to it:

<IfModule mod_rewrite.c>

Options +FollowSymlinks -Multiviews

RewriteEngine On

rewriteCond %{http_host} ^.xxx.xxx [NC]

rewriteRule ^(.*)$ https://www.xxx.xxx/$1 [R=301,L]

</IfModule>

Then save it, put the .htaccess file in the root directory of the website that needs to jump to the website with www without www, and it will take effect.

In some server configurations, if Options +FollowSymlinks is not set, a 500 error may occur. mod_rewrite needs to have followsymlinks for the rewrite rules to take effect.

-MultiViews means that when accessing objects that are not in the directory, the server will look for files with the same name in the directory.

rewriteCond matches regular %{http_host} ^.xxx.xxx

nc is not case sensitive

rewriteRule rewrite rule is ^(.*)$ http://www.xxx.xxx/$1

R=301 redirection is a 301 jump, you can use the website status query tool to find that the status code of the redirected original address is 301.

l represents the last parsing rules.

In this way, we realize that in the apache2.4 server environment, there is no top-level domain name and the 301 state directly jumps to the second-level domain name with www.

Popular articles
latest article