Using Nginx as a reverse proxy and add source code replacement

Task:

I have web app (in my case Node app running on port 3000)
I would add Nginx in front of it and will serve it on port 80.

Adding reverse proxy config.

Find Nginx.config file by executing: nginx -V

Edit nginx.conf and edit the server section

...
    server {
        listen       8081;
        server_name  toni-develops.com;
        location / {
            proxy_pass http://localhost:3000/;
        }
...

Line 5 tells enginx to intercept all requests / and proxy them from http://localhost:3000
If the request from example is /home Nginx will make request to http://localhost:3000/home

If for example we want to proxy only specific urls (let’s say only *.php) we could do this:

location ~ \.php {
    proxy_pass http://localhost:3000/
}

Add source code replacement

Nginx has to be built with sub_filter module.
The example below will override all localhost:3000 to toni-develops.com:80

...

server {
    listen       8081;
    server_name  toni-develops.com;


    location / {
        proxy_pass http://localhost:3000/;
        proxy_set_header Accept-Encoding "";
        proxy_buffers 8 1024k;  
        proxy_buffer_size 1024k;
        sub_filter 'localhost:3000'  'toni-develops.com:80';
        sub_filter_once off;            
    }

...

 

Leave a Reply