Redirect HTTP to HTTPS using Nginx
Environment: CentOS Linux / Nginx
Reference: https://www.nginx.com/resources/wiki/start/topics/tutorials/install/
Step 1: Create and add CentOS yum repository:
vi /etc/yum.repos.d/nginx.repo
---------------------------------------------------------------------------------------------------------
[nginx]
name= nginx repo baseurl=https://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=0
enabled=1
---------------------------------------------------------------------------------------------------------
Step 2: Install nginx:
sudo yum update
sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
Step 3: Browse or curl to test nginx webpage:
curl localhost
Step 4: Update Nginx configuration:
server {
server_name localhost;
listen 80;
return 301 https://$host$request_uri;
}
server {
server_name localhost;
listen 443 ssl;
index index.html index.html index.php;
access_log /var/log/nginx/localweb.log;
error_log /var/log/nginx/localerr.log;
root /usr/share/nginx/html;
# SSL Certificate configuration
ssl_certificate /etc/nginx/ssl/chaincertificate.crt;
ssl_certificate_key /etc/nginx/ssl/private.key;
proxy_set_header Accept-Encoding "";
sub_filter_types 'text/css';
sub_filter_types 'text/js';
sub_filter_types 'text/json';
sub_filter_types 'application/json';
sub_filter_types 'application/javascript';
sub_filter 'http://localhost' 'https://$host';
sub_filter 'http://localhost' 'https://localhost';
sub_filter_once off;
location / {
try_files $uri $uri/ /index.html?/$request_uri;
}
location /app/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# IP and port number
proxy_pass http://localhost:8080/app/;
proxy_read_timeout 90;
proxy_http_version 1.1;
proxy_request_buffering off;
}
location /app/app1/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# IP and port number
proxy_pass http://localhost:8090/app/app1;
proxy_read_timeout 90;
proxy_http_version 1.1;
proxy_request_buffering off;
}
}
Step 5: Restart nginx:
sudo systemctl restart nginx