Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Nginx]常见业务场景配置指南 #30

Open
PeterChen1997 opened this issue Sep 28, 2021 · 0 comments
Open

[Nginx]常见业务场景配置指南 #30

PeterChen1997 opened this issue Sep 28, 2021 · 0 comments
Labels

Comments

@PeterChen1997
Copy link
Owner

场景

1. 代理域名到目标 CDN

说明:

  • 使用 proxy_pass 代理请求到目标 CDN

配置:

location / {
    proxy_pass http://static-nginx-test.oss-cn-beijing.aliyuncs.com/xxx/index.html;  
}

2. 前后端分离配置

说明:

  • /api 后的内容指向 server 端
  • / 直接返回 CDN 内容

配置:

location /api/ {
     proxy_set_header X-Origin-Host $host;
     proxy_set_header X-Forwarded-For $remote_addr;
     proxy_set_header Host xxx;
     proxy_next_upstream error invalid_header http_502 http_503;
     proxy_next_upstream_tries 3;
     proxy_pass http://soho-test-ingress/; 
     client_max_body_size 50M;
}
    
location / {
    proxy_pass http://static-nginx-test.oss-cn-beijing.aliyuncs.com/xxx/; 
}

3. 支持 browser router

说明:

  • 不缓存 html 文件(与此场景配置无关)
  • /xxx 的 path 默认指向 HTML,由 HTML 进行路由解析
  • 对于请求的资源文件,需要额外配置解析规则,否则会指向 HTML 文件
  • 使用正则匹配资源后,由于资源为 /assets/xxx.js 无法直接使用 $1 (xxx.js) 进行跳转
    • 使用 $uri 读取当前 url,进行拼接
    • 使用 rewrite,拿到完整 url,修改配合 break 进行 CDN 目标资源的跳转

配置:

location / {
     if ($request_filename ~ .*\.(htm|html)$)
     {
		     add_header Cache-Control no-cache;
		     expires -1s;
     }
     try_files $uri /index.html;
     proxy_pass https://static-nginx-test.oss-cn-beijing-internal.aliyuncs.com/tutor/tutor-turing-web/;
}

location ~* \.(gif|jpg|png|js|css)$ {
		# 方法一
		rewrite ^/(.*)$ /tutor/tutor-turing-web/$1 break;
		proxy_pass https://static-nginx-test.oss-cn-beijing-internal.aliyuncs.com; 

		# 方法二
		proxy_pass https://static-nginx-test.oss-cn-beijing-internal.aliyuncs.com/tutor/tutor-turing-web$uri;
}

4. http 跳转 https

if ($scheme != "https") {
    rewrite ^ https://$host$uri permanent;
}

坑点

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant