15 April 2015
Sample port redirect using NGINX
A common scenario when using a separate Web Server from an Application Server is port redirect. using NGINX as a web application server and an application server it is possible to redirect incoming requests for specific data retrieved in the server-side via JSON,
- /myapp/rest/ correlates to the designated server side app RESTful endpoint returning data via JSON
- /myapp/image/ correlates to the designated image server endpoint returning images data via bytestream.
In this example we have a NGINX web server listening on port 80 (HTTP) and 443 (HTTPS) which automatically redirects the user connection to HTTPS on port 443. It also demonstrates a tunneling technique where specific URL containing special pathnames makes the server proxy the request to a backend application server listening on port 8181. Here goes a sample NGINX configuration that demonstrates the detailed configuration above:
- To enable HTTPS mode on NGINX first generate a public key using OpenSSL or other tool and point to it from your configuration file.
NGINX - app configuration file
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
server_name localhost;
return 301 https://$server_name$request_uri;
}
server { listen 443 ssl; client_max_body_size 5M;
root /usr/share/nginx/html;
index  index.html index.htm;
# Make site accessible from http://localhost/
server_name localhost;
# SSL configuration
ssl_certificate /etc/nginx/ssl/myapp.crt;
    ssl_certificate_key /etc/nginx/ssl/myapp.key;
    location ~ ^/myapp/rest/ {
        proxy_pass         https://localhost:8181;
        proxy_redirect     off;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }
location ~ ^/myapp/image/ {
        proxy_pass         https://localhost:8181; # image server
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
}
location / {
    try_files $uri $uri/ =404;
    }
}