IT俱乐部 Nginx Nginx反向代理静态文件并修改路径方式

Nginx反向代理静态文件并修改路径方式

Nginx反向代理静态文件并修改路径

Nginx 配置想要将 /a/b/ 的请求代理到本地目录 /abc/ 下的文件。可以在 Nginx 配置中使用 alias 指令来指定一个本地路径作为代理目标。

server {
    listen 8080;

    location / {
        proxy_pass http://192.168.1.100:8080;
    }

    location /a/b/ {
        alias /abc/;
        try_files $uri $uri/ /index.html;
    }
}

解释和注意事项:

  • location /a/b/:这里配置了一个 location 块,用于匹配以 /a/b/ 开头的请求。
  • alias /abc/;:使用 alias 指令指定了本地路径 /abc/ 作为代理目标。当匹配到 /a/b/ 的请求时,Nginx 将会将这些请求映射到本地目录 /abc/
  • try_files $uri $uri/ /index.html;:这里使用了 try_files 指令,用于尝试查找对应的文件。如果请求的文件不存在,则会返回 /index.html

注意:

  • 在使用 alias 指令时,结尾的斜杠 / 是重要的,确保路径设置正确。
  • 需要确保 Nginx 对 /a/b/ 的访问权限和路径配置正确,以及本地目录 /abc/ 中包含所需的静态文件或资源。
  • 配置完成后,重启或重新加载 Nginx,然后尝试访问 /a/b/ 下的资源,它应该会被代理到本地目录 /abc/ 中的对应文件。

Nginx反向代理+路径重写 配置

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        # 访问方式:http://127.0.0.1/1/ng1/ --> http://127.0.0.1:82 这里和方式二主要区别在于rewrite和proxy_pass的位置。
        location ~ /ng1/ {
            proxy_pass http://127.0.0.1:81;
            rewrite "^/(.*)/ng1/(.*)$" /$2 break;
        }
        # 访问方式:http://127.0.0.1/1/ng2/ --> http://127.0.0.1:82
        location ~ /ng2/ {
            rewrite "^/(.*)/ng2/(.*)$" /$2 break;
            proxy_pass http://127.0.0.1:82;
            
        }
        # 访问方式:http://127.0.0.1/ng3/ --> http://127.0.0.1:83
        location /ng3/ {
            rewrite ^/ng3/(.*)$ /$1 break;
            proxy_pass http://127.0.0.1:83;
        }
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/server/nginx/18306.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部