Nginx Proxy Configuration

To configure Nginx as a proxy, use the following configuration

server {
    listen *:80;
    client_max_body_size 100M;
    proxy_read_timeout 600s;
    proxy_buffer_size   128k;
    proxy_buffers   4 256k;
    proxy_busy_buffers_size   256k;
    location / {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://127.0.0.1:81;
    }
}

If you need to serve images using static files, add the following block to Nginx config

    location ~ ^/(images|javascript|js|css|flash|media|static)/ {
        root /home/domain.com/html/;
        index index.php index.html;
        expires 30d;
    }

Rule to handle SSL verification

If you are proxying traffic to an application server, you may need Nginx to handle requests for SSL verification. In that case, add the following to the server block, above location / entry.

    location ~ ^/.well-known/ {
        allow all;
        autoindex on;
        root /var/www/html;
    }

Example

https://gist.github.com/serverok/8fb73df8135774f292bb2cc86446ae2c

Nginx Rails Origin header didn’t match request.base_url

HTTP to HTTPS Redirect

If you do proxying on HTTPS, then you can use the following config for HTTP to handle SSL verification and redirect to HTTPS.

server {
    listen 80;
    server_name YOURDOMAIN.TLD;
    location ~ ^/.well-known/ {
        allow all;
        autoindex on;
        root /var/www/html;
    }
    location / {
        return 301 https://$host$request_uri;
    }
}

Nginx Proxy Config with Caching

Here is Nginx proxy config with caching.

proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=cache:30m max_size=250m;
proxy_temp_path /tmp/nginx_proxy 1 2;

server {
    client_max_body_size 100M;
    location / {
        proxy_pass http://127.0.0.1:8000/;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache cache;
        proxy_cache_bypass $myCookie;
        proxy_no_cache $myCookie;
        proxy_cache_valid 30m;
        proxy_cache_key $host$scheme$proxy_host$request_uri;
        # force caching
        # proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
    }
}

If cookie “myCookie” is present, nginx won’t serve the cached page to that visitor.

Back to Nginx

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *