Nginx服务的启动
# 使用nginx的时候启动服务使用命令行,在nginx的文件下
# 例如nginx文件在 D:\tools\nginx-1.17.2
cd /d D:\tools\nginx-1.17.2
# 启动nginx
.\nginx.exe
# 测试配置文件
.\nginx.exe -t
# 重启nginx
.\nginx.exe -s reload
# 关闭nginx
.\nginx.exe -s stop
Nginx的基础配置和使用
纯静态项目基础使用
server {
listen 80; # 默认80端口监听
server_name juejin.cn; # 解析域名
# index 和root 也可以写在这里 当全局配置
location / {
root html/www;
index index.html index.html; # 默认解析文件
}
}
vue项目history模式使用
server {
listen 80; # 默认80端口监听
server_name juejin.cn; # 解析域名
location / {
root html/www;
try_files $uri $uri/ /index.html;
}
}
前端访问路径为二级目录
server {
listen 80; # 默认80端口监听
server_name juejin.cn; # 解析域名
# 常规使用,前端是一个静态目录
location /admin {
alias html/www;
index index.html index.html; # 默认解析文件
}
#如果前端是一个服务例如nuxt
location ^~/admin/ {
proxy_pass http://192.168.22.166:8080/admin/;
# nuxt项目如果需要获取域名 nginx 可以传递
proxy_set_header Host $http_host;
}
}
前端配置目录里面添加排除项
server {
listen 80; # 默认80端口监听
server_name juejin.cn; # 解析域名
location ^~/admin/ {
if ( $request_uri ~* ^(/admin/engin|/admin/coupon)) {
# 匹配 /admin/engin 和 /admin/coupon 走这里
proxy_pass http://192.168.22.166:3000;
}
proxy_pass http://192.168.22.166:8080/admin/;
}
}
前后端域名相同情况下使用二级目录使用接口
server {
# 正常写法
location /api {
proxy_pass http://127.0.0.1;
}
# 重写写法 重写去掉api
location /api {
proxy_pass https://juejin.cn;
rewrite ^/api(.*)$ $1 break;
}
}
配置同域名二级目录转发自本地(开发常用)
server {
# 根目录自来本地
location / {
proxy_pass http://127.0.0.1;
}
# api目录来自其他服务
location /api {
proxy_set_header Host $host;
proxy_set_header Referer $http_referer;
proxy_set_header Cookie $http_cookie;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass https://192.168.17.149:443;
}
}
nginx区分pc和移动端
# upstream 负载均衡写法 一般配合weight使用 这里不展开
upstream hqchippc {
server 192.168.22.170:3000;
}
upstream hqchipm {
server 192.168.22.170:3001;
}
set $is_mobile no;
if ($http_user_agent ~* "(mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)") {
set $is_mobile yes;
}
location / {
if ($is_mobile = 'yes') {
proxy_pass http://hqchipm;
}
proxy_pass http://hqchippc;
}
配置https
# 这个配置内容是将http请求转到https
server {
listen 80;
server_name www.elecfans.com;
rewrite ^(.*)$ https://$host$1 permanent; # 将请求转成https
}
server {
listen 443; # https 端口是443
server_name www.elecfans.com;
ssl on;
ssl_certificate /home/ce/www.elecfans.com.pem; #ssl证书的pem文件路径
ssl_certificate_key /home/ce/www.elecfans.com.key; #ssl证书的key文件路径
ssl_session_timeout 5m; # 会话超期时间 可不设置
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # 加密版本 可不设置
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-RSA-AES128-SHA"; # 加密设置 按需要配置
ssl_prefer_server_ciphers on;
location / {
root html/www;
index index.html index.html; # 默认解析文件
}
}
Nginx下载
nginx下载地址