AI摘要
本文介绍了如何在nginx的反向代理配置中,设置直接访问某个文件或者文件夹的方法。作者给出了具体的配置方法,并且提供了一些示例,例如针对特定文件的配置、针对特定文件类型的配置等。通过这些配置,可以在代理docker或者node项目时,免去跨域请求的问题。
This article introduces how to set up direct access to a specific file or folder in nginx’s reverse proxy configuration. The author provides specific configuration methods and examples, such as configuring for specific files or file types. With these configurations, the issue of cross-domain requests can be eliminated when proxying docker or node projects.
例如,目前我的反向代理配置如下:
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';
}
在以上配置中,我的这个域名的所有请求,都会被转发到 http://127.0.0.1:5000
,但是我有一个页面,比如update.html
,我不希望被转发,我希望直接访问某个文件,那么,需要按照以下方式在nginx
的配置文件中添加配置
location = /update.html { #这里是你需要直接访问的链接后缀
alias /www/wwwroot/example.com/example.html;#这里是你文件的详细目录
}
不止html,其他文件也可以,例如:
location = /favicon.ico {
alias /www/wwwroot/example.com/favicon.ico;
}
location = /robots.txt {
alias /www/wwwroot/example.com/robots.txt;
}
当你想让某一类文件都指向某个目录时,可以使用下面语句
location ~* /\.(gif|jpg|png|css|js)$ {
alias /www/wwwroot/example.com/static/;
expires 1h; # 缓存1小时
add_header Cache-Control "public"; #设置了缓存并添加了响应头,以便将其暴露给客户端
}