Nginx 常用配置

怼烎@ 2022-10-15 09:00 275阅读 0赞

Nginx是web服务、反向代理、缓存、负载平衡、媒体流等方面的开源软件,同时也提供了 IMAP/POP3/SMTP 服务,其因丰富的功能集、稳定性、示例配置文件和低系统资源的消耗受到了开发者的欢迎。在这篇文章中,我将提到一些我们经常使用的Nginx配置。

1、监听端口

  1. server {
  2. # Standard HTTP Protocol
  3. listen 80;
  4. # Standard HTTPS Protocol
  5. listen 443 ssl;
  6. # For http2
  7. listen 443 ssl http2;
  8. # Listen on 80 using IPv6
  9. listen [::]:80;
  10. # Listen only on using IPv6
  11. listen [::]:80 ipv6only=on;
  12. }

2、访问日志

  1. server {
  2. # Relative or full path to log file
  3. access_log /path/to/file.log;
  4. # Turn 'on' or 'off'
  5. access_log on;
  6. }

3、域名

  1. server {
  2. # Listen to yourdomain.com
  3. server_name yourdomain.com;
  4. # Listen to multiple domains server_name yourdomain.com www.yourdomain.com;
  5. # Listen to all domains
  6. server_name *.yourdomain.com;
  7. # Listen to all top-level domains
  8. server_name yourdomain.*;
  9. # Listen to unspecified Hostnames (Listens to IP address itself)
  10. server_name "";
  11. }

4、静态资源

  1. server {
  2. listen 80;
  3. server_name yourdomain.com;
  4. location / {
  5. root /path/to/website;
  6. }
  7. }

5、重定向

  1. server {
  2. listen 80;
  3. server_name www.yourdomain.com;
  4. return 301 http://yourdomain.com$request_uri;
  5. }
  6. server {
  7. listen 80;
  8. server_name www.yourdomain.com;
  9. location /redirect-url {
  10. return 301 http://otherdomain.com;
  11. }
  12. }

6、反向代理

  1. server {
  2. listen 80;
  3. server_name yourdomain.com;
  4. location / {
  5. proxy_pass http://0.0.0.0:3000;
  6. # where 0.0.0.0:3000 is your application server (Ex: node.js) bound on 0.0.0.0 listening on port 3000
  7. }
  8. }

7、负载均衡

  1. upstream node_js {
  2. server 0.0.0.0:3000;
  3. server 0.0.0.0:4000;
  4. server 123.131.121.122;
  5. }
  6. server {
  7. listen 80;
  8. server_name yourdomain.com;
  9. location / {
  10. proxy_pass http://node_js;
  11. }
  12. }

8、SSL 协议

  1. server {
  2. listen 443 ssl;
  3. server_name yourdomain.com;
  4. ssl on;
  5. ssl_certificate /path/to/cert.pem;
  6. ssl_certificate_key /path/to/privatekey.pem;
  7. ssl_stapling on;
  8. ssl_stapling_verify on;
  9. ssl_trusted_certificate /path/to/fullchain.pem;
  10. ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  11. ssl_session_timeout 1h;
  12. ssl_session_cache shared:SSL:50m;
  13. add_header Strict-Transport-Security max-age=15768000;
  14. }
  15. # Permanent Redirect for HTTP to HTTPS
  16. server {
  17. listen 80;
  18. server_name yourdomain.com;
  19. return 301 https://$host$request_uri;
  20. }

发表评论

表情:
评论列表 (有 0 条评论,275人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Nginx 配置

    Nginx是web服务、反向代理、缓存、负载平衡、媒体流等方面的开源软件,同时也提供了 IMAP/POP3/SMTP 服务,其因丰富的功能集、稳定性、示例配置文件和低系统资源的