前端也应该掌握的Nginx配置

1,139 阅读1分钟

1.多项目管理 - 通过端口实现

在这里我们以80端口和8080端口为例

  • 80端口
server {
    listen    80;
    server_name www.maiyi.com::80;

    location / {
        root /Users/dist; # 项目路径
        index index.html index.htm;
        autoindex on;
	try_files $uri $uri/ /index.html; # 项目重定向
    }
	
    location ^~ /api/ { # 后端接口转发
	include /usr/local/etc/nginx/fastcgi.conf;
        fastcgi_intercept_errors on;
	proxy_pass http://127.0.0.1:9000;
    }
}
  • 8080端口
server {
    listen    8080;
    server_name www.maiyi.com::8080;

    location / {
        root /Users/distAdmin; # 项目路径
        index index.html index.htm;
        autoindex on;
	try_files $uri $uri/ /index.html; # 项目重定向
    }
	
    location ^~ /api/ { # 后端接口转发
	include /usr/local/etc/nginx/fastcgi.conf;
        fastcgi_intercept_errors on;
	proxy_pass http://127.0.0.1:9000/;
    }
}

需要注意的是,在 proxy_pass 中地址末尾的 / 显示问题如下:

http://127.0.0.1:9000; # => http://127.0.0.1:9000/api/...
http://127.0.0.1:9000/; # => http://127.0.0.1:9000/...

2.vue history模式下刷新页面报404

  • 在nginx配置重定向:解决刷新报404问题
location / {
    #...
    try_files $uri $uri/ /index.html; # 项目重定向
}
  • 将打包文件路径改为绝对路径:解决 Uncaught SyntaxError: Unexpected token < 报错问题
module.exports = {
    // ...
    publicPath: '/',
}

3.报错

nginx: [emerg] unknown directive "锘? in D:\nginx-1.12.2/conf/nginx.conf:3 原因是使用了电脑自带的记事本,编辑之后保存会将 utf-8 格式保存成 utf-8 Bom 格式。


nginx: [error] ReadFile() "D:\php\nginx-1.14.2/conf/servers/.." failed (1: Incorrect function) win环境下启用nginx报错,原因是 nginx.conf 配置中存在 /*,被认为是不安全的,需要改成 /*.conf