前言
前端常用的一些nginx配置
基本配置
1 2 3 4 5 6 7 8 9
| server { listen 80; server_name www.ouyanting.com; root /opt/www/file;
location / { index index.html; } }
|
监听其他端口
我想用www.ouyanting.com:8081的形式访问自己博客。对应nginx配置如下。
1 2 3 4 5 6 7 8 9 10
| server { # 这里监听的是8081的端口,可以改成你想监听的其他端口 listen 8081; server_name www.ouyanting.com; root /opt/www/file;
location / { index index.html; } }
|
假如你想要的是www.ouyanting.com:80的话listen对应的是80,但在浏览器当中默认是省略调80的。
同一域名访问不同的文件夹
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| server { # 这里监听的是8081的端口,可以改成你想监听的其他端口 listen 8081; server_name www.ouyanting.com; root /opt/www/a;
# www.ouyanting.com 访问a文件夹 location / { index index.html; }
# www.ouyanting.com/b 访问b文件夹 location /b { # 指向b文件夹 alias /opt/www/b/; }
# www.ouyanting.com/c 访问c文件夹 location /c { # 指向c文件夹 alias /opt/www/c/; } }
|
判断PC还是手机
假如我自己分别开发了手机端跟PC端的页面。但是老板说无论手机还是PC,点击https://www.ouyanting.com就自动跳转到对应端的页面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| server { listen 80; server_name www.ouyanting.com; # 指向PC端文件夹 root /opt/www/web;
location / { # 判断是否是移动端 if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) { # 重写URL rewrite ^(.*) $scheme://www.ouyanting.com/h5$1 permanent; } index index.html; }
location /h5/ { # 判断是否PC端 if ($http_user_agent !~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) { # 重写URL rewrite ^/h5(.*)$ $scheme://www.ouyanting.com$1 permanent; } # 指向移动端文件夹 alias /opt/www/h5/; } }
|
反向代理解决跨域问题
假如我在本地要请求https://api.ouyanting.com/api/getUser
这个接口。VSCODE开服务访问index.html文件。浏览器访问地址为localhost:5500。在已经违反了同源策略的了。在后端没开启CORS的情况下,是会提示跨域的。如何配置nginx解决跨域问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| server { listen 80; server_name www.ouyanting.com;
location / { proxy_pass http://localhost:5500; }
# 这里将`/api`指向到`https://api.ouyanting.com/` # 也就是`http://localhost:5500/api/getUser`等于`https://api.ouyanting.com/getUser` # `http://localhost:5500/api/api/getUser`等于`https://api.ouyanting.com/api/getUser` location /agentApi { proxy_pass https://api.ouyanting.com/; } }
|
上面配置后假如后端出了个接口给我地址是https://api.ouyanting.com/api/getUserList
,我需要用ajax去请求该接口获得参数。
正常来说是用以下代码去获取数据的。但由于本地是http://localhost:5500
,协议、域名、端口不同,不同源,后端没开启CORS的话,会提示跨域。
1.81 2 3 4
| $.get("https://api.ouyanting.com/api/getUserList", function(resp) { console.log("获取数据", resp); });
|
上面配置nginx后,就可以将请求代码改为如下。即可。
1.81 2 3 4
| $.get("/agentApi/api/getUserList", function(resp) { console.log("获取数据", resp); });
|
对比两部分代码只有请求URL是改变了而已。
代理前(https://api.ouyanting.com/api/getUserList
)跟代理后(/agentApi/api/getUserList
)
他们相同的部分为/api/getUserList
这部分我们就暂时不理。
那剩下的就是代理前(https://api.ouyanting.com
)跟代理后(/agentApi
)
/agentApi
也就等于http://localhost:5500/agentApi
由于nginx配置中有这样一句话。
1 2 3
| location /agentApi { proxy_pass https://api.ouyanting.com/; }
|
这样就会匹配进入到location /agentApi
的配置里,他会转发/代理到https://api.ouyanting.com/
上。也就是代理后的/agentApi/api/getUserList == http://localhost:5500/agentApi/api/getUserList == https://api.ouyanting.com/api/getUserList
如果还有什么不懂的话,欢迎留言,或者给我发邮件。