您的位置:首页 > 运维架构 > Nginx

nginx(11) nginx 配置动静分离,设置默认主页,限制某个路径的资源代理全解

2016-12-27 16:37 651 查看
一,所有接口请求都反向代理,静态资源单独设置路径

1.绕过动态代理设置默认主页

正常情况下,配置完location的root后,默认主页直接会取root指定路径的index.html index.php等作为默认主页

以域名http://demo.williamy.xin:8090/ 为例

现在做了反向代理, 输入域名会访问自己的动态服务路径为  /

upstream demo.williamy.xin{
server 127.0.0.1:8060 weight=1;
}
server {
listen       8090;
server_name  upstream demo.williamy.xin;

#charset koi8-r;

#access_log  logs/host.access.log  main;

location / {
proxy_http_version 1.1;
proxy_pass http://demo.williamy.xin; proxy_redirect default;
proxy_connect_timeout 1s;
proxy_read_timeout 5s;
proxy_send_timeout 2s;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
add_header 'Access-Control-Allow-Headers' 'Content-Type';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';
}
location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|mp3|mp4)$
{    #index index2.html;
root /data/web/demo/static_src;
expires      14d;
}


上面的配置有个小问题,输入域名直接会访问http://demo.williamy.xin:8060/  而不是http://demo.williamy.xin:8090/index.html



现在将 / 这个访问用正则表达式严格限制出来

添加

location ~ ^/$
{
root /data/web/demo/static_src;
}
即可,这样 ~表示nginx要用正则表达式,  ^代表正则表达式的开始,$代表正则表达式的结尾

这个配置会让访问直接去

root /data/web/demo/static_src
寻找index.html



2.让某个文件夹下的静态资源单独访问

因为配置了html,css,png,js等走静态路径,但是动态服务本身有些功能比如自己的后台希望走自己本身的资源路径,目前我的方式是设置单独的路径,单独配置一段nginx

location ~ /mg/+ {
proxy_pass http://demo.williamy.xin; }


二,制定默认访问静态资源,后台接口使用某个路径访问

upstream bao.mac{
server 127.0.0.1:8080 weight=1;
}
server {
listen 8081;
server_name localhost;
location / {
root /Users/bao/data/static_src;
index index.html index.htm;
}
location /s1 {
proxy_pass http://bao.mac; }
三,其他

location ^~ /static_js/

{

proxy_cache js_cache;

proxy_set_header Host gao.test.com;

proxy_pass http://gao.test.com/; }
如上面的配置,如果请求的url是http://servername/static_js/test.html
会被代理成http://gao.test.com/test.html
而如果这么配置
location ^~ /static_js/

{

proxy_cache js_cache;

proxy_set_header Host gao.test.com;

proxy_pass http://gao.test.com; }
则会被代理到http://gao.test.com/static_js/test.htm
当然,我们可以用如下的rewrite来实现/的功能
location ^~ /static_js/

{

proxy_cache js_cache;

proxy_set_header Host gao.test.com;

rewrite /static_js/(.+)$ /$1 break;

proxy_pass http://gao.test.com; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  域名 linux nginx
相关文章推荐