nginx实用配置用例
vue项目部署及后台api访问
nginx.conf
# vue本地项目配置
...
server {
listen 8000;
server_name localhost;
root /.../dist; # vue资源根目录
index index.html;
location / {
try_files $uri $uri/ @router;
index index.html;
}
location @router {
rewrite ^.*$ /index.html last;
}
location /api {
# 配置代理
proxy_pass API地址; # http://0.0.0.0:8080/api
}
}
...
配置静态页面访问
server {
listen 80; # 默认端口是80,如果端口没被占用可以不用修改
server_name domain.com www.domain.com;
#charset koi8-r;
#access_log logs/host.access.log main;
root .../dist/; # 项目的资源目录
location / {
try_files $uri $uri/ @router; # 需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
index index.html index.htm;
}
#对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
#因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
rewrite ^.*$ /index.html last;
}
}
配置SSL证书,实现HTTPS访问
这里用配置wordpress为例
server{
listen 80; #表示监听80端口
server_name domain.com www.domain.com;
location / { #将80端口强制转为https
rewrite (.*) https://www.domain.com$1 permanent;
}
}
server {
listen 443;
server_name www.domain.com domain.com;
ssl on;
ssl_certificate /root/ssl/证书文件.crt;
ssl_certificate_key /root/ssl/证书文件.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #按照这个协议配置
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;#按照这个套件配置
ssl_prefer_server_ciphers on;
location / {
root /root/blog; # 项目根目录
index index.php;
}
location ~ .*\.(php|php5)?$ {
root /root/blog;
fastcgi_pass 127.0.0.1:9000; # 服务监听端口
fastcgi_index index.php;
include fastcgi.conf;
}
}
一台服务器上面部署多个服务,根据域名访问
域名一:
upstream domain1 {
server 127.0.0.1:3000;
}
server {
listen 80;
server_name domain1.com;
location / {
proxy_pass http://domain1/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
域名二:
upstream domain2 {
server 127.0.0.1:4000;
}
server {
listen 80;
server_name www.domain2.com domain2.com;
location / {
proxy_pass http://domain2/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}