Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to proxy web apps using nginx?

Virtual Hosts on nginx (CSC309)

When hosting our web applications, we often have one public IP address (i.e., an IP address visible to the outside world) using which we want to host multiple web apps. For example, one may wants to host three different web apps respectively for example1.com, example2.com, and example1.com/images on the same machine using a single IP address.

How can we do that? Well, the good news is Internet browsers send the domain name inside HTTP requests and all we need to do is to parse the requested domain name and URL and then route the HTTP request to the actual web server.

Oh, do I really need to parse HTTP requests? You can if you really want to, but there are lots of tools and technologies that readily do this for you. In this tutorial, we walk you through how you can use nginx to proxy multiple web applications.

Install nginx

CDF @UofT

We have prepared pre-copmiled binaries for your. You need to download nginx.tar.gz and uncompress it:

$ wget http://www.cs.toronto.edu/~soheil/csc309/nginx.tar.gz && tar -xvzf nginx.tar.gz
  • It creates an nginx directory for you. The config file is in nginx/conf/nginx.conf.
  • We have provided a script named nginx in the directory. To run nginx, go to the nginx directory (cd nginx) and run ./nginx ....

Ubuntu

Install nginx using apt-get:

$ sudo apt-get install nginx

Notes:

  • The part of the nginx's config file we need resides in /etc/nginx/sites-enabled/default.
  • To edit the config file or run nginx, you need to use sudo.

Mac OS

Install homebrew, and then install nginx using brew:

$ brew install nginx

Notes:

  • nginx's config file is in /usr/local/etc/nginx/nginx.conf.
  • To edit the config file or run nginx, you need to use sudo: sudo nano /usr/local/etc/nginx/nginx.conf and sudo nginx ...

Configuration

Step 1 -- Booting Servers for Virtual Hosts

Write three different node applications running on different ports (say 8080, 8181, 8282) on your machine.

Step 2 -- Configure nginx's Port

To do so, you need to edit your nginx config file.

In the config file, find the server section:

server {
    listen       80;
    ...
    location / {
       ...
    }
    ...
}

If you're using CDF, make sure you change 80 to a vacant port number (ask for one from your instructor). If not, you can keep using 80 or change the port if you will.

Test nginx

  1. Run ./nginx on CDF, or run sudo nginx on your local machine.
  2. Open the browser and log on to localhost:$PORT (replace $PORT with the port number you configured for nginx).

Step 3 -- Configure /

Let say we want to configure nginx to route requests for /, /blog, and /mail, respectively onto localhost:8080, localhost:8181, and localhost:8282.

                  +--- host --------> node.js on localhost:8080
                  |
users --> nginx --|--- host/blog ---> node.js on localhost:8181
                  |
                  +--- host/mail ---> node.js on localhost:8282

To route /, you need to edit your nginx config file.

In the config file, find the server section:

server {
    listen       80;
    ...
    location / {
       ...
    }
    ...
}

This section is simply telling nginx how it should serve HTTP requests.

Now, change the location section to this snippet:

server {
    listen       ...;
    ...
    location / {
        proxy_pass http://127.0.0.1:8080;
    }
    ...
}

proxy_pass simply tells nginx to forward requests to / to the server listening on http://127.0.0.1:8080.

Step 4 -- Reload nginx's Configuration

To reload nginx's configuration run: nginx -s reload on your machine.

Referesh your browser. Do you see the output from your node.js application? If yes, you are all set. If no, there is a problem with your config.

Step 5 -- Add /blog and /mail

To redirect /mail and /blog, you simply need to add new entries the location section in the config file:

server {
    listen       ...;
    ...
    location / {
        proxy_pass http://127.0.0.1:8080;
    }
    
    location /blog {
        proxy_pass http://127.0.0.1:8181;
    }

    location /mail {
        proxy_pass http://127.0.0.1:8282;
    }
    ...
}

Step 6 -- Reload Your nginx Configuration

Run nginx -s reload on your machine.

Log onto localhost:$PORT/blog in your browser. Do you see the output from your second node.js application?

Then log onto localhost:$PORT/mail. Do you see the output from your third node.js application?

If yes & yes, you are all set. If no, there is a problem with your config.

Step 7 -- Rewriting Requests

Now as you might have noticed in Step 6, nginx sends the same HTTP request to your node.js web apps which results into a 404 error. Why? Because, your node.js web application serves requests from / not from /blog and /mail. But, nginx is sending requests to /blog and /mail.

To fix this issue, we need rewrite the URL so that it matches the URL you can serve on your node.js applications.

To correctly rewrite URLs change your config file to match the following snippet:

server {
    listen       ...;
    ...
    location / {
        proxy_pass http://127.0.0.1:8080;
    }
    
    location /blog {
        rewrite ^/blog(.*) /$1 break;
        proxy_pass http://127.0.0.1:8181;
    }

    location /mail {
        rewrite ^/mail(.*) /$1 break;
        proxy_pass http://127.0.0.1:8282;
    }
    ...
}

This rewrite commands are simple regular expressions that transform strings like /blogWHAT_EVER and /mailWHAT_EVER to /WHAT_EVER in the HTTP requests.

Step 8 -- Reload and Test.

All set?

Exercise 1

Configure your nginx to redirect URLs from /google to http://www.google.com

Step 9 (optional) -- Redirecting Based on Host Name

Let say you want to host example1.com, example2.com, and example3.com on your machine, respectively to localhost:8080, localhost:8181, and localhost:8282.

Note: Since you don't have access to a DNS server, you should add domain name entries to your /etc/hosts (you can't do this on CDF machines):

...
127.0.0.1 example1.com example2.com example3.com
...

To proxy eaxmple1.com we can't use the location part of the default server. Instead we need to add another server section with a server_name set to our virtual host (e.g., example1.com, ...), and then a simple location section that tells nginx how to proxy the requests:

server {
    listen       80;
    server_name  example1.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
    }
}

server {
    listen       80;
    server_name  example2.com;

    location / {
        proxy_pass http://127.0.0.1:8181;
    }
}

server {
    listen       80;
    server_name  example3.com;

    location / {
        proxy_pass http://127.0.0.1:8282;
    }
}

Simple, ha?!

@pravinbashyal

This comment has been minimized.

Show comment
Hide comment
@pravinbashyal

pravinbashyal Feb 16, 2015

yes it is simple... thanks a lot... it was very helpful...

pravinbashyal commented Feb 16, 2015

yes it is simple... thanks a lot... it was very helpful...

@n4nagappan

This comment has been minimized.

Show comment
Hide comment
@n4nagappan

n4nagappan Mar 8, 2015

Very useful post ! I had to re-write the url for NodeJS app.

n4nagappan commented Mar 8, 2015

Very useful post ! I had to re-write the url for NodeJS app.

@fliiiix

This comment has been minimized.

Show comment
Hide comment
@fliiiix

fliiiix Apr 25, 2015

Awesome, thanks ❤️

fliiiix commented Apr 25, 2015

Awesome, thanks ❤️

@mech

This comment has been minimized.

Show comment
Hide comment
@mech

mech May 5, 2015

If my blog app itself has a path like this http://127.0.0.1:8181/articles/2014, does that means the public will see the path as http://host.com/blog/articles/2014?

mech commented May 5, 2015

If my blog app itself has a path like this http://127.0.0.1:8181/articles/2014, does that means the public will see the path as http://host.com/blog/articles/2014?

@saydulk

This comment has been minimized.

Show comment
Hide comment
@saydulk

saydulk Jul 10, 2015

This is not working for me-

There are three application both running by python on ubuntu 14.4. they are visible as below link

http://82.211.213.130:8181 (headphones)
http://82.211.213.130:8081 (sickbeard)
http://82.211.213.130:5050 (couchpotato)

i have also installed HTTPS on that server.
https://82.211.213.130/

But i want to rewrite above three site in the bellow way

same IP/couchpotato -- this is working only
same IP/sickbeard -- Not working
same IP/headphones -- not working

when i want to view /sickbeard or /headphones it allways comes couchpotato page.

help me any one to solve this?

Apache config is as below --

<VirtualHost *:443>
DocumentRoot /var/www/html
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/ssl.crt
SSLCertificateKeyFile /etc/apache2/ssl/ssl.key
SSLCertificateChainFile /etc/apache2/ssl/sub.class1.server.ca.pem

<VirtualHost :443>
ServerName lost-world.dk
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/ssl.crt
SSLCertificateKeyFile /etc/apache2/ssl/ssl.key
SSLCertificateChainFile /etc/apache2/ssl/sub.class1.server.ca.pem
RewriteEngine On
RewriteRule ^/(.
) localhost:5050/$1 [L,P]
ProxyPreserveHost on

RequestHeader add X-Vhm-Root /couchpotato

<VirtualHost :443>
ServerName lost-world.dk
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/ssl.crt
SSLCertificateKeyFile /etc/apache2/ssl/ssl.key
SSLCertificateChainFile /etc/apache2/ssl/sub.class1.server.ca.pem
RewriteEngine On
RewriteRule ^/(.
) localhost:8081/$1 [L,P]
ProxyPreserveHost on

RequestHeader add X-Vhm-Root /sickbeard

saydulk commented Jul 10, 2015

This is not working for me-

There are three application both running by python on ubuntu 14.4. they are visible as below link

http://82.211.213.130:8181 (headphones)
http://82.211.213.130:8081 (sickbeard)
http://82.211.213.130:5050 (couchpotato)

i have also installed HTTPS on that server.
https://82.211.213.130/

But i want to rewrite above three site in the bellow way

same IP/couchpotato -- this is working only
same IP/sickbeard -- Not working
same IP/headphones -- not working

when i want to view /sickbeard or /headphones it allways comes couchpotato page.

help me any one to solve this?

Apache config is as below --

<VirtualHost *:443>
DocumentRoot /var/www/html
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/ssl.crt
SSLCertificateKeyFile /etc/apache2/ssl/ssl.key
SSLCertificateChainFile /etc/apache2/ssl/sub.class1.server.ca.pem

<VirtualHost :443>
ServerName lost-world.dk
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/ssl.crt
SSLCertificateKeyFile /etc/apache2/ssl/ssl.key
SSLCertificateChainFile /etc/apache2/ssl/sub.class1.server.ca.pem
RewriteEngine On
RewriteRule ^/(.
) localhost:5050/$1 [L,P]
ProxyPreserveHost on

RequestHeader add X-Vhm-Root /couchpotato

<VirtualHost :443>
ServerName lost-world.dk
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/ssl.crt
SSLCertificateKeyFile /etc/apache2/ssl/ssl.key
SSLCertificateChainFile /etc/apache2/ssl/sub.class1.server.ca.pem
RewriteEngine On
RewriteRule ^/(.
) localhost:8081/$1 [L,P]
ProxyPreserveHost on

RequestHeader add X-Vhm-Root /sickbeard

@tugberkugurlu

This comment has been minimized.

Show comment
Hide comment
@tugberkugurlu

tugberkugurlu Nov 17, 2015

This is a fantastic resource, thx for this!

tugberkugurlu commented Nov 17, 2015

This is a fantastic resource, thx for this!

@imakshath

This comment has been minimized.

Show comment
Hide comment
@imakshath

imakshath Feb 12, 2016

Nice one. Thanks a lot 👍

imakshath commented Feb 12, 2016

Nice one. Thanks a lot 👍

@hengkiardo

This comment has been minimized.

Show comment
Hide comment
@hengkiardo

hengkiardo Feb 15, 2016

how about the static files, like css/images/js??

hengkiardo commented Feb 15, 2016

how about the static files, like css/images/js??

@sujayy1983

This comment has been minimized.

Show comment
Hide comment
@sujayy1983

sujayy1983 Feb 15, 2016

Neat explanation. Thanks a lot!

sujayy1983 commented Feb 15, 2016

Neat explanation. Thanks a lot!

@Demon-Hunter

This comment has been minimized.

Show comment
Hide comment
@Demon-Hunter

Demon-Hunter Feb 26, 2016

Very nice! Thank you!

Demon-Hunter commented Feb 26, 2016

Very nice! Thank you!

@lawenliu

This comment has been minimized.

Show comment
Hide comment
@lawenliu

lawenliu Mar 1, 2016

Great help! Thanks a lot.

lawenliu commented Mar 1, 2016

Great help! Thanks a lot.

@vikashvikram

This comment has been minimized.

Show comment
Hide comment
@vikashvikram

vikashvikram Mar 2, 2016

Clean, concise and effective. Really helped me in deploying my rails apps. Thanks. I had to make one change though - somehow rewrite part was redirecting the requests to location /. So ran my rails servers on suburls itself.

vikashvikram commented Mar 2, 2016

Clean, concise and effective. Really helped me in deploying my rails apps. Thanks. I had to make one change though - somehow rewrite part was redirecting the requests to location /. So ran my rails servers on suburls itself.

@willjharmer

This comment has been minimized.

Show comment
Hide comment
@willjharmer

willjharmer Mar 3, 2016

Brill post. Thanks, solves my proxying problem perfectly.

willjharmer commented Mar 3, 2016

Brill post. Thanks, solves my proxying problem perfectly.

@vimalprakashts

This comment has been minimized.

Show comment
Hide comment
@vimalprakashts

vimalprakashts Mar 9, 2016

very nice, thank you 👍

vimalprakashts commented Mar 9, 2016

very nice, thank you 👍

@vimalprakashts

This comment has been minimized.

Show comment
Hide comment
@vimalprakashts

vimalprakashts Mar 10, 2016

The step 5 not working for me.

vimalprakashts commented Mar 10, 2016

The step 5 not working for me.

@thecatontheflat

This comment has been minimized.

Show comment
Hide comment
@thecatontheflat

thecatontheflat commented May 18, 2016

Thanks!

@youyaochi

This comment has been minimized.

Show comment
Hide comment
@youyaochi

youyaochi Jun 22, 2016

you saved my ass, thank you!

youyaochi commented Jun 22, 2016

you saved my ass, thank you!

@ngerritsen

This comment has been minimized.

Show comment
Hide comment
@ngerritsen

ngerritsen Jul 3, 2016

This was exactly what I was looking for! My home server running several web apps and services like utorrent server and plex. This saves me from opening all those ports and enabling to set up a single ssl

ngerritsen commented Jul 3, 2016

This was exactly what I was looking for! My home server running several web apps and services like utorrent server and plex. This saves me from opening all those ports and enabling to set up a single ssl

@kkworden

This comment has been minimized.

Show comment
Hide comment
@kkworden

kkworden Jul 13, 2016

Thank you! :D

kkworden commented Jul 13, 2016

Thank you! :D

@mmubasher

This comment has been minimized.

Show comment
Hide comment
@mmubasher

mmubasher Jul 31, 2016

You have not replied to a single comment. Did you copy pasted this from somewhere?

mmubasher commented Jul 31, 2016

You have not replied to a single comment. Did you copy pasted this from somewhere?

@puneetsngh

This comment has been minimized.

Show comment
Hide comment
@puneetsngh

puneetsngh Aug 14, 2016

thanx, this works for me, 1 thing I want to know...is there any disadvantages in this approach? Will my server get expose for any attacks?

puneetsngh commented Aug 14, 2016

thanx, this works for me, 1 thing I want to know...is there any disadvantages in this approach? Will my server get expose for any attacks?

@aprilandjan

This comment has been minimized.

Show comment
Hide comment
@aprilandjan

aprilandjan Sep 12, 2016

This is the best article about nginx I'm looking for, thank you bro!

aprilandjan commented Sep 12, 2016

This is the best article about nginx I'm looking for, thank you bro!

@akuisara

This comment has been minimized.

Show comment
Hide comment
@akuisara

akuisara commented Sep 13, 2016

Thanks!

@akivahe

This comment has been minimized.

Show comment
Hide comment
@akivahe

akivahe Nov 4, 2016

thanks tons

akivahe commented Nov 4, 2016

thanks tons

@exrobbie

This comment has been minimized.

Show comment
Hide comment
@exrobbie

exrobbie commented Nov 16, 2016

Nice!

@SleepingPanda

This comment has been minimized.

Show comment
Hide comment
@SleepingPanda

SleepingPanda Dec 22, 2016

Thanks! This works brilliantly!

SleepingPanda commented Dec 22, 2016

Thanks! This works brilliantly!

@andresmgsl

This comment has been minimized.

Show comment
Hide comment
@andresmgsl

andresmgsl Jan 8, 2017

Thanks a lot

andresmgsl commented Jan 8, 2017

Thanks a lot

@Nekowei

This comment has been minimized.

Show comment
Hide comment
@Nekowei

Nekowei Jan 23, 2017

A lot help! Thanks!

Nekowei commented Jan 23, 2017

A lot help! Thanks!

@bertalanimre

This comment has been minimized.

Show comment
Hide comment
@bertalanimre

bertalanimre Feb 1, 2017

Love you Mate. :D Thanks for this tutorial.

bertalanimre commented Feb 1, 2017

Love you Mate. :D Thanks for this tutorial.

@double-o-z

This comment has been minimized.

Show comment
Hide comment
@double-o-z

double-o-z Feb 19, 2017

Very straightforward and handy,
Thanks a bunch.

double-o-z commented Feb 19, 2017

Very straightforward and handy,
Thanks a bunch.

@ppKrauss

This comment has been minimized.

Show comment
Hide comment
@ppKrauss

ppKrauss Feb 21, 2017

To use try_files with proxy, some caution... Example: the simplest way to show static page at root and use proxy to another requisition,

location / {
    try_files $uri $uri/ @proxy;
}
location @proxy {
    proxy_pass  http://127.0.0.1:3000;
    ...
}

See http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

ppKrauss commented Feb 21, 2017

To use try_files with proxy, some caution... Example: the simplest way to show static page at root and use proxy to another requisition,

location / {
    try_files $uri $uri/ @proxy;
}
location @proxy {
    proxy_pass  http://127.0.0.1:3000;
    ...
}

See http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

@EricPobot

This comment has been minimized.

Show comment
Hide comment
@EricPobot

EricPobot Feb 27, 2017

According to http://serverfault.com/a/725433 it seems that the step 7 can be done without URL rewriting and thus better perfs.

Any thought on this ?

EricPobot commented Feb 27, 2017

According to http://serverfault.com/a/725433 it seems that the step 7 can be done without URL rewriting and thus better perfs.

Any thought on this ?

@javyzheng

This comment has been minimized.

Show comment
Hide comment
@javyzheng

javyzheng Mar 22, 2017

I am using nginx/1.11.5, and I want /log to be mapped to something like http://127.0.0.1:8181, but

    location /blog {
        proxy_pass http://127.0.0.1:8181;
    }

the above config will map the request to http://127.0.0.1:8181/blog.

If I want to map /log to http://127.0.0.1:8181, I need to add a slash at the end of the target url.

    location /blog {
        proxy_pass http://127.0.0.1:8181/;
    }

javyzheng commented Mar 22, 2017

I am using nginx/1.11.5, and I want /log to be mapped to something like http://127.0.0.1:8181, but

    location /blog {
        proxy_pass http://127.0.0.1:8181;
    }

the above config will map the request to http://127.0.0.1:8181/blog.

If I want to map /log to http://127.0.0.1:8181, I need to add a slash at the end of the target url.

    location /blog {
        proxy_pass http://127.0.0.1:8181/;
    }
@k4rz4

This comment has been minimized.

Show comment
Hide comment
@k4rz4

k4rz4 Mar 31, 2017

Hi,
What if i have 20 aplications and i don't want to open 20 ports, how i can manipulate with static files like css, js ... I am talking about public access. How to serve those kind of files?

Thanks in advance

k4rz4 commented Mar 31, 2017

Hi,
What if i have 20 aplications and i don't want to open 20 ports, how i can manipulate with static files like css, js ... I am talking about public access. How to serve those kind of files?

Thanks in advance

@ShreeshaN

This comment has been minimized.

Show comment
Hide comment
@ShreeshaN

ShreeshaN Apr 8, 2017

Thanks for the tutorial buddy :)

ShreeshaN commented Apr 8, 2017

Thanks for the tutorial buddy :)

@hoandang

This comment has been minimized.

Show comment
Hide comment
@hoandang

hoandang Apr 16, 2017

By following the tutorial, I was able to redirect the / to /foo but static assets still remain under / . Has anyone got the same problem?

hoandang commented Apr 16, 2017

By following the tutorial, I was able to redirect the / to /foo but static assets still remain under / . Has anyone got the same problem?

@ietuday

This comment has been minimized.

Show comment
Hide comment
@ietuday

ietuday Apr 19, 2017

Hi Guys,

I was running four node servers using

Configuring multiple applications on same port using nginx reverse proxy based on request urls

its working but the bundles files cannot loaded. I am stuck. Please Help

on Browser Console

Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/inline.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/scripts.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/vendor.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/main.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/styles.bundle.css Failed to load resource: the server responded with a status of 404 (Not Found)

ietuday commented Apr 19, 2017

Hi Guys,

I was running four node servers using

Configuring multiple applications on same port using nginx reverse proxy based on request urls

its working but the bundles files cannot loaded. I am stuck. Please Help

on Browser Console

Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/inline.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/scripts.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/vendor.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/main.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/styles.bundle.css Failed to load resource: the server responded with a status of 404 (Not Found)

@walterpinson

This comment has been minimized.

Show comment
Hide comment
@walterpinson

walterpinson May 22, 2017

I'm having the exact problem @ietuday. Have you resolved it?

walterpinson commented May 22, 2017

I'm having the exact problem @ietuday. Have you resolved it?

@Tom32i

This comment has been minimized.

Show comment
Hide comment
@Tom32i

Tom32i May 23, 2017

@soheilhy Thank you for this! 🙏

Tom32i commented May 23, 2017

@soheilhy Thank you for this! 🙏

@bapjiws

This comment has been minimized.

Show comment
Hide comment
@bapjiws

bapjiws May 26, 2017

@hoandang I was having the same problem as you. My index.html was loaded correctly from the right location served by proxy_pass, but the static files were still being (or rather, not being) served from the root path no matter what. I solved this (totally not sure if that's the most elegant solution out there) by injecting the absolute path to all the necessary static resources into the index.html file.

bapjiws commented May 26, 2017

@hoandang I was having the same problem as you. My index.html was loaded correctly from the right location served by proxy_pass, but the static files were still being (or rather, not being) served from the root path no matter what. I solved this (totally not sure if that's the most elegant solution out there) by injecting the absolute path to all the necessary static resources into the index.html file.

@ArfanMirza

This comment has been minimized.

Show comment
Hide comment
@ArfanMirza

ArfanMirza Jun 1, 2017

First of all, Thanks to @ppKrauss suggestion help me here!
@ietuday, @walterpinson have you solved path for static assets ?

if not then try this

location / {

	root /var/www/xxx/xxx;
        
	proxy_pass http://site.com:8111;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
        try_files $uri $uri/ $uri:8111 @proxy_assets;
    }
	location @proxy_assets{
		proxy_pass http://site.com:8111; # put here you static url path... 
	}

This worked for me!

ArfanMirza commented Jun 1, 2017

First of all, Thanks to @ppKrauss suggestion help me here!
@ietuday, @walterpinson have you solved path for static assets ?

if not then try this

location / {

	root /var/www/xxx/xxx;
        
	proxy_pass http://site.com:8111;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
        try_files $uri $uri/ $uri:8111 @proxy_assets;
    }
	location @proxy_assets{
		proxy_pass http://site.com:8111; # put here you static url path... 
	}

This worked for me!

@edwardboyle

This comment has been minimized.

Show comment
Hide comment
@edwardboyle

edwardboyle Sep 5, 2017

Thank you for taking the time to write this.

edwardboyle commented Sep 5, 2017

Thank you for taking the time to write this.

@sisingh

This comment has been minimized.

Show comment
Hide comment
@sisingh

sisingh Nov 4, 2017

Great article. One correction though. I have hosted my REST APIs on port 9090 as well. Now when I was redirecting I was getting 404 error as it was putting two slashes. This is one of the biggest difference between URI and URL :) If you want to redirect to URI, you need to remove one slash. For e.g, rewrite ^/blog(.) /$1 break; should be changed to rewrite ^/blog(.) $1 break;
Remove '/' before $1.

sisingh commented Nov 4, 2017

Great article. One correction though. I have hosted my REST APIs on port 9090 as well. Now when I was redirecting I was getting 404 error as it was putting two slashes. This is one of the biggest difference between URI and URL :) If you want to redirect to URI, you need to remove one slash. For e.g, rewrite ^/blog(.) /$1 break; should be changed to rewrite ^/blog(.) $1 break;
Remove '/' before $1.

@absolutelynotjames

This comment has been minimized.

Show comment
Hide comment
@absolutelynotjames

absolutelynotjames Nov 10, 2017

Fantastic resource, thank you!

absolutelynotjames commented Nov 10, 2017

Fantastic resource, thank you!

@testups

This comment has been minimized.

Show comment
Hide comment
@testups

testups Nov 16, 2017

in this case how can i write nginx configuration?
i have multiple paths on a single domain and using single port in nginx configuration with nodejs application

can any one assist, how to write nginx configuration?

thanks inadvance!

testups commented Nov 16, 2017

in this case how can i write nginx configuration?
i have multiple paths on a single domain and using single port in nginx configuration with nodejs application

can any one assist, how to write nginx configuration?

thanks inadvance!

@seanmatabs

This comment has been minimized.

Show comment
Hide comment
@seanmatabs

seanmatabs Dec 5, 2017

Best and Most Helpful Doc I have gone thru in 2017! Thanks!

seanmatabs commented Dec 5, 2017

Best and Most Helpful Doc I have gone thru in 2017! Thanks!

@danimerida2000

This comment has been minimized.

Show comment
Hide comment
@danimerida2000

danimerida2000 Jan 3, 2018

This article is straightforward and important for devops tools, thanks a lot!!

danimerida2000 commented Jan 3, 2018

This article is straightforward and important for devops tools, thanks a lot!!

@Jonarod

This comment has been minimized.

Show comment
Hide comment
@Jonarod

Jonarod Jan 9, 2018

If you install from Linux using sudo apt-get install nginx, beware that there is a small annoying bug starting from 1.8 version you can see here. In fact, when you start nginx using sudo nginx you might get the following error:

nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] still could not bind()

To solve it, you should either :
sudo killall nginx
OR
delete the /etc/init/nginx.conf file
before starting nginx server.
Then, everything works fine :)

Jonarod commented Jan 9, 2018

If you install from Linux using sudo apt-get install nginx, beware that there is a small annoying bug starting from 1.8 version you can see here. In fact, when you start nginx using sudo nginx you might get the following error:

nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] still could not bind()

To solve it, you should either :
sudo killall nginx
OR
delete the /etc/init/nginx.conf file
before starting nginx server.
Then, everything works fine :)

@jackiilong

This comment has been minimized.

Show comment
Hide comment
@jackiilong

jackiilong Jan 14, 2018

very helpful.thanks!

jackiilong commented Jan 14, 2018

very helpful.thanks!

@E1101

This comment has been minimized.

Show comment
Hide comment
@E1101

E1101 Jan 24, 2018

how to proxy all requests except home?

thanks.

E1101 commented Jan 24, 2018

how to proxy all requests except home?

thanks.

@aweijnitz

This comment has been minimized.

Show comment
Hide comment
@aweijnitz

aweijnitz Feb 8, 2018

Super useful advice and a very straightforward explanation. Many thanks! The comment from @sisingh above should be worked into the example, as it leaves the request intact and doesn't add any extra slashes.

aweijnitz commented Feb 8, 2018

Super useful advice and a very straightforward explanation. Many thanks! The comment from @sisingh above should be worked into the example, as it leaves the request intact and doesn't add any extra slashes.

@dirtyhandsphp

This comment has been minimized.

Show comment
Hide comment
@dirtyhandsphp

dirtyhandsphp Mar 27, 2018

@javyzheng: Thanks, your comment helped me to fix my proxy issue.

dirtyhandsphp commented Mar 27, 2018

@javyzheng: Thanks, your comment helped me to fix my proxy issue.

@bystefu

This comment has been minimized.

Show comment
Hide comment
@bystefu

bystefu Mar 28, 2018

I have current configuration, for proxy and stream url from youtube

  location /youtube/{
    proxy_pass https://r3---sn-bungvh5op5-vu2e.googlevideo.com/videoplayback?mm=31%2C29&mn=sn-bungvh5op5-vu2e%2Csn-4g5ednsd&dur=202.200&id=o-AFjWapRU1oF1Y-Evp11775fwUeYsTVXA07Oq_P38SNtk&key=yt6&ip=178.156.230.108&lmt=1521800310735142&pcm2cms=yes&mt=1522248524&source=youtube&mv=u&ms=au%2Crdu&fvip=1&sparams=aitags%2Cclen%2Cdur%2Cei%2Cgir%2Cid%2Cip%2Cipbits%2Citag%2Ckeepalive%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Crequiressl%2Csource%2Cexpire&ipbits=0&requiressl=yes&keepalive=yes&mime=video%2Fmp4&aitags=133%2C134%2C135%2C136%2C137%2C160%2C242%2C243%2C244%2C247%2C248%2C278&c=WEB&expire=1522270274&pl=23&ei=4qu7Wtt6wuxb8eqmuAY&clen=39808074&itag=137&gir=yes&signature=69B7807E757AC495764075666FC46FB4087EC9EA.09F95DC4C08979277FE9A9F535354A4F0E52FF3D&ratebypass=yes/;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_buffering on;
    proxy_connect_timeout 75;
    proxy_send_timeout 180;
    proxy_read_timeout 1200;
    keepalive_timeout 120;
    proxy_buffer_size 128k;
    proxy_buffers 4 256k;
    proxy_busy_buffers_size 256k;
  }

But not working, i get 400 error (but in all browser's work), and i don't know response is from my server or from google. I tried also proxy_pass http://youtube.com/watch?x=x and i get a 404 error from google, page watch not exist. I'm new in all that, nginx, reverse_proxy. I guess the url going from me is not correct. Sorry for my eng.

bystefu commented Mar 28, 2018

I have current configuration, for proxy and stream url from youtube

  location /youtube/{
    proxy_pass https://r3---sn-bungvh5op5-vu2e.googlevideo.com/videoplayback?mm=31%2C29&mn=sn-bungvh5op5-vu2e%2Csn-4g5ednsd&dur=202.200&id=o-AFjWapRU1oF1Y-Evp11775fwUeYsTVXA07Oq_P38SNtk&key=yt6&ip=178.156.230.108&lmt=1521800310735142&pcm2cms=yes&mt=1522248524&source=youtube&mv=u&ms=au%2Crdu&fvip=1&sparams=aitags%2Cclen%2Cdur%2Cei%2Cgir%2Cid%2Cip%2Cipbits%2Citag%2Ckeepalive%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Crequiressl%2Csource%2Cexpire&ipbits=0&requiressl=yes&keepalive=yes&mime=video%2Fmp4&aitags=133%2C134%2C135%2C136%2C137%2C160%2C242%2C243%2C244%2C247%2C248%2C278&c=WEB&expire=1522270274&pl=23&ei=4qu7Wtt6wuxb8eqmuAY&clen=39808074&itag=137&gir=yes&signature=69B7807E757AC495764075666FC46FB4087EC9EA.09F95DC4C08979277FE9A9F535354A4F0E52FF3D&ratebypass=yes/;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_buffering on;
    proxy_connect_timeout 75;
    proxy_send_timeout 180;
    proxy_read_timeout 1200;
    keepalive_timeout 120;
    proxy_buffer_size 128k;
    proxy_buffers 4 256k;
    proxy_busy_buffers_size 256k;
  }

But not working, i get 400 error (but in all browser's work), and i don't know response is from my server or from google. I tried also proxy_pass http://youtube.com/watch?x=x and i get a 404 error from google, page watch not exist. I'm new in all that, nginx, reverse_proxy. I guess the url going from me is not correct. Sorry for my eng.

@johnnyfekete

This comment has been minimized.

Show comment
Hide comment
@johnnyfekete

johnnyfekete Apr 11, 2018

Thank you for the description! It has a lot of explanation, not just code, and really saved my day!
Everything worked on the first try!

johnnyfekete commented Apr 11, 2018

Thank you for the description! It has a lot of explanation, not just code, and really saved my day!
Everything worked on the first try!

@skpk

This comment has been minimized.

Show comment
Hide comment
@skpk

skpk May 13, 2018

I am getting error on which nginx proxy_pass excluding some urls:
when i goto /path/stuff it must proxy
if i give /path/stuff/var1/ then it must not proxy_pass

location /path/stuff (!/|/) {
proxy_pass some-url;
}

when i get the url as

/path/stuff = proxy_pass;
/path/stuff/var1 = must open the same(no need proxy_pass);
/path/stuff/abc = proxy_pass;
/path/stuff/var2 = must open the same(no need proxy_pass);
/path/stuff/ngin = proxy_pass:

skpk commented May 13, 2018

I am getting error on which nginx proxy_pass excluding some urls:
when i goto /path/stuff it must proxy
if i give /path/stuff/var1/ then it must not proxy_pass

location /path/stuff (!/|/) {
proxy_pass some-url;
}

when i get the url as

/path/stuff = proxy_pass;
/path/stuff/var1 = must open the same(no need proxy_pass);
/path/stuff/abc = proxy_pass;
/path/stuff/var2 = must open the same(no need proxy_pass);
/path/stuff/ngin = proxy_pass:

@hugobcar

This comment has been minimized.

Show comment
Hide comment
@hugobcar

hugobcar Jun 8, 2018

Thanks for your post

hugobcar commented Jun 8, 2018

Thanks for your post

@anestin-femi

This comment has been minimized.

Show comment
Hide comment
@anestin-femi

anestin-femi Jun 20, 2018

If you were a girl, I would have kissed your hands like right now. I have trying to get this for 1 full week right now and none of them worked. Thank you very much. You are a live saver. Thanks a quintillion times.

anestin-femi commented Jun 20, 2018

If you were a girl, I would have kissed your hands like right now. I have trying to get this for 1 full week right now and none of them worked. Thank you very much. You are a live saver. Thanks a quintillion times.

@flashjpr

This comment has been minimized.

Show comment
Hide comment
@flashjpr

flashjpr Jul 6, 2018

Thanks a ton for your effort in writing this amazingly easy to comprehend guide!

flashjpr commented Jul 6, 2018

Thanks a ton for your effort in writing this amazingly easy to comprehend guide!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment