If you need to change the URL of a page in search engine results, Google recommends that you use the 301 redirect. This is the best way to ensure that users and search engines are directed to the correct page as well to prevent your website from a traffic loss.
To set up the redirect from HTTP to HTTPS, you need to use mod_rewrite
:
LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so
For the changes to take effect, we need to reload the Apache web server:
apache2ctl restart
Add to the .htaccess:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.sitename\.com$ [NC]
RewriteRule ^(.*)$ http://sitename.com/$1 [R=301,L]
Or:
RewriteEngine On
Redirect 301 / http://sitename.com/
The best way is to configure redirects with separate vhost-s
.
vhost is the virtual host for the domain. It starts with a section server {
and can be used in the main configuration file nginx.conf
or through including as an external file, for example: include sites-enabled/*.conf;
If you do not need to redirect to www or non-www:
server {
listen x.x.x.x:80;
server_name sitename.com;
server_name www.sitename.com;
return 301 https://$server_name$request_uri;
}
If you need to redirect to www or non-www.
Redirecting to www.sitename.com:
server {
listen x.x.x.x:80;
server_name sitename.com;
server_name www.sitename.com;
return 301 https://www.sitename.com$request_uri;
}
Redirecting to non-www:
server {
listen x.x.x.x:80;
server_name sitename.com;
server_name www.sitename.com;
return 301 https://sitename.com$request_uri;
}
If you need to redirect https non-www to https: // www. :
server {
listen x.x.x.x:443 ssl http2;
server_name sitename.com;
ssl_certificate /path/to/cert.....;
ssl_certificate_key /path/to/key...;
return 301 https://www.sitename.com$request_uri;
}
server {
listen x.x.x.x:443 ssl http2;
server_name www.sitename.com;
ssl_certificate /path/to/cert.....;
ssl_certificate_key /path/to/key...;
root /path/to/docroot;
...
...
}
To implement a redirect within one vhost, when there is no possibility to use several (for example, a control panel on the server is used ):
server {
listen x.x.x.x:80;
listen x.x.x.x:443 ssl http2;
server_name www.domain.com;
ssl_certificate /path/to/cert.....;
ssl_certificate_key /path/to/key...;
root /path/to/docroot;
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
...
...
}