How to Master Reverse Proxy with Nginx: From Hosts to CORS
This guide explains the concepts of forward and reverse proxies, shows how to modify the hosts file for domain binding, walks through installing and configuring Nginx as a reverse proxy, and demonstrates creating a cross‑origin setup with frontend and backend code, including CORS handling and WebSocket support.
What Is a Proxy?
Before discussing reverse proxies, we need to understand what a proxy is.
Forward Proxy
Example: you want to give flowers to a colleague but avoid direct rejection, so you ask another teammate to deliver them. The teammate acts as a forward proxy, forwarding your request to the target. In the Internet, forward proxies are used for bypassing firewalls, such as VPN services.
Reverse Proxy
Example: you call 10086, and the telecom assigns a random free customer service representative. The telecom acts as a reverse proxy, receiving your request and forwarding it to an available backend server. Reverse proxies are mainly used for load balancing, selecting an idle server among many to handle a request.
Modify hosts for Domain Binding
On macOS, edit the hosts file:
127.0.0.1 a.com
This maps a.com directly to the local machine without DNS lookup. On Windows, the hosts file is located at C:\Windows\System32\drivers\etc. After editing, verify with ping a.com – it should resolve to 127.0.0.1.
Install Nginx
For macOS, install via Homebrew:
Run
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"to install Homebrew.
Install Nginx with brew install nginx.
Start Nginx using nginx or sudo nginx if permission is required.
After starting, open http://localhost:8080 in a browser to confirm the installation.
Initial Nginx Configuration
Now that a.com resolves to the local machine, configure Nginx to proxy requests.
Visit a.com in a browser – you will see a “cannot access this site” error because no configuration exists yet.
Change to the Nginx configuration directory: cd /usr/local/etc/nginx/servers Create and edit test.conf with the following content:
server { # Listen on port 80 listen 80; # Domain name server_name a.com; location / { proxy_pass https://www.baidu.com; } }
Reload Nginx: nginx -s reload, then refresh the browser. The page should now proxy to Baidu.
Create a Cross‑Domain Environment
We will set up a project structure with separate front‑end and back‑end directories under an nginx folder.
Front‑end code ( ./fe/nginx/index.html) implements a simple CORS test using XMLHttpRequest:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CORS 实现跨域</title> </head> <body> <h3>CORS 实现跨域</h3> <script> var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:8888/api/getFriend'); xhr.setRequestHeader('token', 'quanquanbunengshuo'); xhr.withCredentials = true; xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); console.log(xhr.getAllResponseHeaders()); } }; xhr.send(); </script> </body> </html>
Start the front‑end server with: live-server ./fe/nginx If port 8080 is occupied, specify another port, e.g., live-server ./fe/nginx --port=9999.
Back‑end code ( ./be/nginx/index.js) provides a simple HTTP service:
const http = require('http'); const PORT = 8888; const server = http.createServer((request, response) => { console.log(request.headers); response.end("{name: 'quanquan', friend: 'guiling'}"); }); server.listen(PORT, () => { console.log('服务启动成功, 正在监听: ', PORT); });
Start the back‑end with node ./be/nginx/index.js.
Refine Nginx Configuration
Replace the Baidu upstream with the local front‑end address and add an /api location to forward API calls to the back‑end.
server {
listen 80;
server_name a.com;
location / {
proxy_pass http://127.0.0.1:9999;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /api/ {
proxy_pass http://127.0.0.1:8888;
}
}Reload Nginx with nginx -s reload, then open a.com in a browser. The front‑end page loads, the XHR request is sent to /api/getFriend, which Nginx forwards to the back‑end, and the response appears in the console, completing the cross‑domain demonstration.
To support the WebSocket connections required by live-server, add the following directives inside the location / block:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";The final Nginx configuration file is:
server {
listen 80;
server_name a.com;
location / {
proxy_pass http://127.0.0.1:9999;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /api/ {
proxy_pass http://127.0.0.1:8888;
}
}All code and project files are available at https://github.com/luoquanquan/cross-domain .
Conclusion
The Nginx reverse proxy tricks the browser into thinking the API is same‑origin, while the server actually forwards the request to a different service, similar to how a telecom operator assigns a random customer service representative.
Author: 圈圈的圈
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
