How to reverse proxy and setup SSL certificate using Nginx config file:
Nginx is one of best application server available for hosting application on Ubuntu server. In this article, I will guide to setup reverse proxy and SSL certificate using Nginx config file.
We are running our application on port 8000 on the local server. It is not publicly exposed. We will be exposing this publicly on SSL port.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
server_tokens off; # for security-by-obscurity: stop displaying nginx version # this section is needed to proxy web-socket connections map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { gzip on; gzip_http_version 1.1; gzip_vary on; gzip_comp_level 6; gzip_proxied any; gzip_types text/plain text/html text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js; gzip_buffers 16 8k; gzip_disable "MSIE [1-6]\.(?!.*SV1)"; listen 80; if ($scheme = http) { return 301 https://$server_name$request_uri; } listen 443 ssl; ssl_certificate /etc/letsencrypt/example.com/fullchain.pem; //full chain of ssl ceriticate ssl_certificate_key /etc/letsencrypt/example.com/privkey.pem; //private key ssl_protocols SSLv3 TLSv1; ssl_ciphers HIGH:!aNULL:!MD5; server_name example.com www.example.com; if ($host = 'example.com' ) { rewrite ^/(.*)$ https://www.example.com/$1 permanent; } location / { proxy_pass http://127.0.0.1:8000; // host address inside the private server. proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. } } |
Let me explain main parts of this config file in parts.
If any request that comes to non SSL port redirect to secure SSL port.
1 2 3 4 |
listen 80; if ($scheme = http) { return 301 https://$server_name$request_uri; } |
Apply SSL certificate :
1 2 3 4 |
ssl_certificate /etc/letsencrypt/example.com/fullchain.pem; //full chain of ssl ceriticate ssl_certificate_key /etc/letsencrypt/example.com/privkey.pem; //private key ssl_protocols SSLv3 TLSv1; ssl_ciphers HIGH:!aNULL:!MD5; |
Setup reverse proxy:
1 2 3 4 5 6 7 8 9 10 |
location / { proxy_pass http://127.0.0.1:8000; // host address inside the private server. proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. } |
Let me know if you have questions. Thank you.
Share this post with friends if you find this helpful.