How to Redirect HTTP Requests to HTTPS?

19-01-2024 05:26:46

This article demonstrates how to redirect HTTP requests to HTTPS, assuming an HTTPS website is already configured. For example, if our domain is zhaomu.com, we need to redirect HTTP requests from http://www.zhaomu.com to https://www.zhaomu.com. The procedures for Apache and Nginx servers are outlined below.

Apache Server

Method 1

Create a .htaccess file in the root directory of the site with the following content:

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

Method 2

Add the following code to the Apache configuration file:

<VirtualHost *:80>
    ServerName zhaomu.com
    ServerAlias www.zhaomu.com
    Redirect 301 / https://www.zhaomu.com/
</VirtualHost>

Nginx Server

Add the following code to the Nginx server's configuration file:

server {
    listen 80;
    server_name zhaomu.com www.zhaomu.com;
    return 301 https://www.zhaomu.com$request_uri;
}

Note: After setting up, it is necessary to restart Apache or Nginx for the changes to take effect.