Redirecting requests to SSL

I will describe several options for redirecting requests from HTTP to HTTPS, the first and second methods are the most reliable:

1) Across virtual hosts.
In the site configuration, add the line “Redirect”, for example, when an SSL certificate was installed on the site and you need to redirect all requests to HTTPS:

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName ixnfo.com
   ServerAlias www.ixnfo.com
   Redirect / https://ixnfo.com/
</VirtualHost>

<VirtualHost *:443>
   ServerName ixnfo.com
   ServerAlias www.ixnfo.com
   DocumentRoot /var/www/html
   SSLEngine On
   ...
</VirtualHost>

If you want to redirect only some requests:

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName ixnfo.com
   ServerAlias www.ixnfo.com
   Redirect /forum https://forum.ixnfo.com/
</VirtualHost>

<VirtualHost *:443>
   ServerName ixnfo.com
   ServerAlias www.ixnfo.com
   DocumentRoot /var/www/html
   SSLEngine On
   ...
</VirtualHost>

2) Redirecting using .htaccess.
Similarly, as in the first version, put the .htaccess file in the desired directory of the site and add a line to it (so that the web server takes into account the .htaccess file, you need to specify the option AllowOverride All in the site configuration above):

Redirect /forum https://forum.ixnfo.com/

3) And not the recommended way, using mod_rewrite, the content should be added to the .htaccess file:

# Enabling the Rewrite function
RewriteEngine On
# Verify that the connection is not HTTPS
RewriteCond %{HTTPS} !=on
# We are sending to the same place, but already HTTPS:
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

Another example:

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_USER_AGENT} ^(.+)$
RewriteCond %{SERVER_NAME} ^ixnfo\.com$ [OR]
RewriteCond %{SERVER_NAME} ^www\.ixnfo\.com$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Header add Strict-Transport-Security "max-age=300"
</IfModule>

To allow some pages to open via http and https, add the following in the top example:

RewriteCond %{REQUEST_URI} !^/dir/
RewriteCond %{REQUEST_URI} !^/dir/file.php

See also:
Using .htaccess
How to configure SSL and HTTPS for WordPress
Installing Certbot in Ubuntu

Leave a comment

Leave a Reply