前端使用nginx配置跨域代理

140 阅读1分钟

1、下载nginx,自行搜索下载

2、打开nginx安装目录下的conf文件,再打开nginx.conf进行配置

主要配置server部分,#后面的是注释

server {
        # 监听端口
        listen       8999;
        server_name  localhost;
        #charset koi8-r;
​
        #access_log  logs/host.access.log  main;
        location / {
            # proxy_pass http://localhost:5500/;
            # proxy_pass http://localhost:5173/;
            # 项目地址(也可以设置项目启动的服务地址)
            root D:\code\add;
            # 首页
            index home.html;
            # add_header Access-Control-Allow-Origin *;
        }
        # 代理地址
        location /koa-api/ {
        # 跨域的API接口地址
        # 设置完成之后,把原本的api接口地址改为 http://127.0.0.1:8999/koa-api/xxx
        # 之后访问项目地址使用:http:127.0.1:8999访问
            proxy_pass http://xxx-center.qianxi5.com/;
        }
​
        #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;
        }
​
        # 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$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
​
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
    }

3、配置完成之后,在此处打开cmd,输入 start nginx

image.png 4、打开浏览器,输入localhost,出现如下界面代表启动成功

image.png

常用命令

开启nginx

start nginx

重启nginx(用于修改nginx.conf之后重启)

nginx -s reload

关闭nginx

nginx -s stop