5

Redirect HTTP Requests To HTTPS On Nginx

 2 years ago
source link: https://www.vultr.com/docs/redirect-http-requests-to-https-on-nginx
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
<?xml encoding="utf-8" ??>

Introduction

This Quickstart guide describes how to redirect non-secure HTTP requests to secure HTTPS on Nginx.

Prerequisites

  • You have a Vultr Linux instance running Nginx.
  • You have a domain name (e.g example.com), whose DNS A records for "@" and "www" point to the IP of your instance.
  • Ideally, you should also have a valid SSL certificate installed on your instance. See our guide to install a free Let's Encrypt certificate.

Configure the Redirect

Locate your server block configuration file. By default, this is /etc/nginx/nginx.conf, however it's common for that file to have an include directive:

include /etc/nginx/conf.d/*.conf;

If you have a similar line, you may need to review several files in /etc/nginx/conf.d/ to locate the listen 80 (HTTP) server block for your site. You may have multiple blocks or files if you host multiple sites.

Step by Step

The basic steps are:

  1. Adjust your listen 80 server block to redirect all traffic to HTTPS. Add a line similar to this:

    return 301 https://example.com$request_uri;
    
  2. Add a listen 443 ssl server block to handle the HTTPS traffic. Move any statements needed from your listen 80 server block to this new block.

Example

Here is a simplified example of both blocks. Note that both http://example.com and http://www.example.com will redirect to https://example.com.

http {
    server {
        listen 80;
        server_name example.com www.example.com;

        # Redirect all port 80 (HTTP) requests to port 443 (HTTPS).
        return 301 https://example.com$request_uri;
    }

    server {
        listen 443 ssl;
        server_name example.com;

        ssl_certificate     /path/to/cert-crt.crt;
        ssl_certificate_key /path/to/cert-key.key;

        # all other site settings go here (e.g. ssl, logs, site root)
    }
}

Additional Resources

For more information about how to configure server blocks, see the Nginx documentation and this detailed nginx.conf example file.

Want to contribute?

You could earn up to $600 by adding new articles


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK