Nginx Force HTTPS, HTTP 301 Redirect to HTTPS

Publish: 2016-05-24 | Modify: 2018-11-04

Enable HTTPS for Your Website

Enabling HTTPS for your website can make it more secure. In this article, we will share a method to redirect all HTTP requests to HTTPS by configuring the web server (Nginx) directly, without making too many changes to the program settings. This method is currently used by XiaoZ's blog.

nginx_580

Prerequisites

This method is only applicable to the Nginx web server. We recommend installing LNMP or OneinStack, or you can also compile and install Nginx on your own.

Modify the Host Configuration File

For LNMP or OneinStack, the configuration file is located at /usr/local/nginx/conf/vhost/yourdomain.com.conf. Add the following configuration to the file:

server
{
        listen 80;
        server_name xiaoz.me www.xiaoz.me;
        rewrite ^(.*) https://blog.xiaoz.org$1 permanent;
}

The above configuration means that when we use HTTP to request xiaoz.me or www.xiaoz.me, it will be redirected to https://blog.xiaoz.org. Below is a complete configuration file for reference:

server {
listen 443;
ssl on;
ssl_certificate /data/ssl/xiaoz.me.crt;
ssl_certificate_key /data/ssl/xiaoz.me.key;
server_name xiaoz.me www.xiaoz.me;
index index.html index.htm index.php;
...
...
}

server
{
        listen 80;
        server_name xiaoz.me www.xiaoz.me;
        rewrite ^(.*) https://blog.xiaoz.org$1 permanent;
}

After modifying the configuration, don't forget to reload Nginx: service nginx reload.

CURL Test

Finally, we can test whether accessing HTTP will be redirected to HTTPS. You can use CURL to test it: curl -I www.xiaoz.me. For a tutorial on configuring SSL for Nginx, you can refer to How to Deploy SSL Certificate for Nginx.

curl_test

Recommended Reading:


Comments