How to Exclude a URL or Page from a Root-Path Reverse Proxy
This post was translated from Chinese by AI. If anything reads oddly, the Chinese original is authoritative. 中文原文
How do I exclude a specific URL or page when reverse proxying the root path?
AI Summary
This article explains how to configure a reverse proxy and direct access to specific files in Nginx. To serve certain pages directly from files, use the
aliasdirective to specify the file path. You can also use thelocationdirective to route requests to different directories based on their extensions, and configure caching and response headers. This is useful for avoiding cross-origin request issues when proxying Docker or Node projects.
For example, my current reverse proxy configuration is:
location ^~ /
{
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_http_version 1.1;
# proxy_hide_header Upgrade;
add_header X-Cache $upstream_cache_status;
#Set Nginx Cache
set $static_filemUUFts6J 0;
if ( $uri ~* "\.(gif|png|jpg|css|js|woff|woff2)$" )
{
set $static_filemUUFts6J 1;
expires 1m;
}
if ( $static_filemUUFts6J = 0 )
{
add_header Cache-Control no-cache;
}
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
With this configuration, all requests to my domain are forwarded to http://127.0.0.1:5000. But if I have a page such as update.html that I want to serve directly from a file instead of forwarding it, I need to add the following to my nginx configuration file
location = /update.html { #This is the URL path you want to access directly
alias /www/wwwroot/example.com/example.html;#This is the full path to your file
}
This works for files other than html too, for example:
location = /favicon.ico {
alias /www/wwwroot/example.com/favicon.ico;
}
location = /robots.txt {
alias /www/wwwroot/example.com/robots.txt;
}
To route all files of certain types to a specific directory, use the following
location ~* /\.(gif|jpg|png|css|js)$ {
alias /www/wwwroot/example.com/static/;
expires 1h; # Cache for 1 hour
add_header Cache-Control "public"; #Configure caching and add a response header to expose it to the client
}
The most convenient part of this configuration is that it saves me from dealing with cross-origin request issues when proxying docker or node projects.
Last updated 2024-01-14
Comments 0