nginx配置及跨域配置

1,266 阅读2分钟

1、Windows环境下使用Nginx

1、下载Nginx并解压,存放路径中不允许出现中文

截图.png

2、在cmd中启动Nginx

cd D:\anzhuangbao\nginx-1.18.0\nginx-1.18.0
start nginx


//其他Nginx命令
nginx -s reload //重启(修改配置文件后需要重启Nginx)
nginx -s stop //停止

3、查看启动Nginx是否成功: tasklist /fi "imagename eq nginx.exe

有时候会启动失败,有可能是端口被占用了 截图 (1).png

解决端口被占用问题

在cmd中输入命令:taskkill /T /F /PID PID号 例如:要中止PID为12744的进程,则输入taskkill /T /F /PID 12744

4、修改nginx配置文件,配置文件为conf下的nginx.conf,修改nginx.conf中的server配置片段

截图 (2).png

5、完成nginx配置后重新加载配置文件,命令如下(ps:需要在安装的根路径下执行):

nginx -s reload

6、浏览器中访问:http://localhost:8888

出现如下界面则成功 image.png

2、跨域配置

截图 (3).png

#允许跨域请求的域,*代表所有
add_header 'Access-Control-Allow-Origin' *;
#允许带上cookie请求
add_header 'Access-Control-Allow-Credentials' 'true';
#允许请求的方法,比如 GET/POST/PUT/DELETE
add_header 'Access-Control-Allow-Methods' *;
#允许请求的header
add_header 'Access-Control-Allow-Headers' *;

3、gzip配置

//在server{ }里面添加如下代码:
# gzip config
gzip on;#开启gzip
gzip_min_length 1k;#低于1kb的资源不压缩
gzip_comp_level 6;#压缩级别【1-9】,越大压缩率越高,同时消耗cpu资源也越多
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript;#需要压缩哪些响应类型的资源,多个空格隔开。不建议压缩图片
gzip_disable "MSIE [1-6]\."; #配置禁用gzip条件,支持正则。此处表示ie6及以下不启用gzip(因为ie低版本不支持)
gzip_http_version 1.1;
gzip_vary on;#是否添加“VaryAccept-Encoding”响应头

判断成功的标记为文件请求后在response header中出现如下标记

截图 (4).png

4、页面刷新404配置

在 server——》location /{ } 中添加如下配置

 location / {
     try_files $uri $uri/ /dist/index.html;
 }
 
 
 //或者
 location / {
    root   html;
    index  index.html index.htm;
    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.html?s=$1 last;
        break;
    }
}