前言
在前端开发过程中经常是需要把前端静态资源放到服务器中,这时经常用到nginx来配置
nginx配置详情:Nginx 中文文档
下面列出几个经常用到的配置
nginx指令
- 启动 nginx: start nginx
- 关闭 nginx: nginx -s stop
- 重启 nginx: nginx -s reload
配置文件 config.conf
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#打开压缩配置
#gzip on;
server {
#监听的端口
listen 80;
# 服务器
server_name localhost;
location / {
root html;
index index.html;
}
}
}
proxy_pass 代理
在前端开发中经常在webpack.config.js的devServer.proxy中设置代理,以便调试接口
在服务器上有可能会静态资源和服务器不同源(协议://域名:端口),这时候就需要用到代理
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html;
}
location /api/ {
# 把 http://localhost/api/ 代理到 http://test.com:8081/api/
# 静态资源请求接口的时候走这里 http://localhost/api/
#实际请求代理到这里 http://test.com:8081/api/
proxy_pass http://test.com:8081/api/
}
}
try_files
会从第一个开始匹配,匹配到最后一个,如果匹配不到重定向到最后一个的参数
server {
listen 80;
server_name localhost;
location /web {
root /workspace;
index test.html;
try_files:$url $url/test.html;
}
}
root 和 alias的区别
server {
listen 80;
server_name localhost;
location /web {
root /workspace;
index test.html;
}
}
在请求 http://hostlocal:80/web 查找静态资源的时候就会到服务器 root+localhost(/workspace/web)查找资源,默认是test.html
server {
listen 80;
server_name localhost;
location /web/ {
alias /workspace/static/;
index test.html;
}
}
在请求 http://hostlocal:80/web/ 查找静态资源的时候就会到服务器 alias (/workspace/static)查找资源,默认是test.html;也就是说alias会替代localhost的路径,实际查找的路径是alias
include
当需要用到导入的配置的时候可以使用include导入文件,看起来更加整洁
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html;
}
}
include config/test1.conf
# include config/*.conf
...
}
和nginx.conf同一文件夹下的config文件夹下的test1.conf文件
# config/test1.conf
server {
listen 80;
server_name localhost;
location /web {
root /workspace;
index test.html;
}
}