nginx 配置反向代理解决请求跨域问题

server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        root
"D:/webserver/phpstudy/WWW";
      
#注释的代码开始
      #location / {
       # index index.html index.htm index.php l.php;
        # autoindex off;
      #}
     #注释的代码结束
# 添加的代码开始 location
/ { proxy_pass http://localhost:8080; # 本地启动的项目服务器 proxy_redirect default; } location ^~ /apis { rewrite ^/apis/(.*)$/$1 break; proxy_pass http://www.xxx.com/; # 后台api接口地址 }
     # 添加的代码结束

#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 "D:/webserver/phpstudy/WWW"; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php(.*)$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_info ^((?U).+\.php)(/?.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }

1、修改完成Nginx配置文件之后需要重启服务

2、如果代理配置正确,此时在浏览器中输入 localhost 打开 其中展示的内容应该是 localhost:8080 下的页面内容

在浏览器中输入 localhost/apis/report/data.json 展示的内容应该是 www.xxx.com/report/data.json 下的json数据。

如果打开这两个页面不是的话,那么就可能是配置错误了

2、我使用的是phpstudy 所以Nginx配置文件是在  其他选项菜单 -> 打开配置文件 -> nginx-conf

3、开始使用反向代理

(1) 本地项目的地址是 localhost:8080 在此项目文件下给 www.xxx.com/report/data.json 发送一个get请求

axios.get('/apis/report/data.json').then((res) => {
  console.log(res)
}).catch((err) => {
  console.log(err)
})

(2) 此时我们如果直接打开 localhost:8080 页面去看,会发现请求失败 会报一个404 的错误代码

(3) 一开始我也没明白,后面才想到,

因为 localhost 的页面内容是localhost:8080的 ,

我就打开了localhost页面 发现请求成功数据接收到了

猜你喜欢

转载自www.cnblogs.com/litings/p/9705663.html