This article gives three examples of Nginx proxy forwarding: forwarding domain name requests to a local port, forwarding domain name requests to another domain name, and forwarding a local port to another port or another domain name.
Forward the domain name request to the local port
First, we will introduce the most commonly used ones. When separating front-end and back-end, sometimes we deploy some services locally such as Node.js as API service. On the local port 3300, assuming the host name is example.com, we need to access All HTTP requests on this host are forwarded to the service deployed at localhost:3300. The configuration can be written as follows:
In this way, when accessing http://api.example.com, it will be forwarded to the local port 3300.
Forward the domain name request to another domain name
Suppose there is an alternate domain name: backup.example.com. When accessing the host backup.example.com, it is directly forwarded to the main domain name example.com. The configuration file can be written as follows:
In this way, when you access http://backup.example.com, it will be forwarded to example.com
Forward a local port to another port or another domain name
Assume that the HTTP service deployed locally needs to be forwarded to port 3300 or other domain names example.com
In this way, when accessing http://localhost, it will be forwarded to the local port 3300 or http://example.com
Note: adding / or not adding / at the end of location
When configuring proxy_pass proxy forwarding, if the following url is added with /
, it indicates the absolute root path; if there is no /, it indicates the relative path.
For example
- with
/
Accessing http://example.com/data/index.html will be forwarded to http://localhost/index.html
- without
/
Accessing http://example.com/data/index.html will be forwarded to http://localhost/data/index.html