Apache and Nginx HTTP(S) non-WWW redirection

Apache NON-WWW Redirection regards to HTTP(s) protocol

With Apache, we can do a 301 redirects from www to a non-www domain (to ensuring only the example.com version is every accessible), using a .htaccess file settings, so first will setting up the HTTP protocol status as a protossl environment variable, like so:

RewriteEngine on

# Set "protossl" to "s" if we were accessed via https://.
RewriteRule ^ - [E=protossl]
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=protossl:s]

# Now we can set safe non-www redirection as 
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

And so we can re access domain through www record as:

RewriteEngine on

# Set "protossl" to "s" if we were accessed via https://.
RewriteRule ^ - [E=protossl]
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=protossl:s]

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Apache HTTP to HTTPS redirection

to make permanent 301 redirection from HTTP to => HTTPS we’ll need to add the following rewrite rule to our .htacess file as:

RewriteEngine On 
RewriteCond %{HTTPS} !=on 
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [L,R=301] 

Check Apache mod_rewrite is enabled

Rewrite rules are depending on mod_rewrite Apache module, so if our rules does not works, we’ll need to check if the module is enabled, and enable it if it’s not.

# for Debian/Ubuntu
sudo a2enmod rewrite

for Centos/Redhat we’ll check if LoadModule rewrite_module modules/mod_rewrite.so is enabled at httpd.conf file.

and so we can check by listing the enabled modules after reload Apache configs.

 

# apache2ctl -M  
or
# httpd -M 

Nginx NON-WWW and HTTPS redirection

Before the main server directive of your virtual server definition /etc/nginx/conf.d/virtual.conf  file, as the following combination…

 

# Redirect http www to https non-www
server {
listen IP:80; 
# listen 80;
server_name www.example.com;
access_log off;
return 301 https://example.com$request_uri;
#return 301 https://$host$request_uri;
}

# Redirect https www to https non-www
server {
listen IP:443;
# listen 443;
server_name example.com;
access_log off;
return 301 https://example.com$request_uri;
#return 301 https://$host$request_uri;
}

# Redirect http no-www to https no-www
server {
listen IP:80 default_server;
# listen [::]:80 default_server;
server_name example.com;
access_log off;
return 301 https://example.com$request_uri;
#return 301 https://$host$request_uri;
}

# So 433 server directive will be the entry server for your website.
server {
listen IP:443 ssl default_server;
#listen [::]:443 ssl default_server;

server_name example.com;

------------------------
------------------------
}

You may also like...

Leave a Reply