Nginx快速入门

212 阅读1分钟

命令

  • 检查配置:nginx -t
  • 重新加载:service nginx reload
  • 查看状态:service nginx status
  • 重启服务:service nginx restart
  • 停止服务:service nginx stop
  • 开启服务:service nginx start
  • 加载其他配置:include vhost/*.conf

配置

前端

http {
    server {
        listen 80;
        server_name webapptest.yhchmo.com;
        access_log /data/wwwlogs/webapptest.yhchmo.com_nginx.log combined;
        index index.html index.htm;
        root /home/wwwroot/webapptest.yhchmo.com;
	}
}

后端

  • 监听80端口

    server {
        listen 80;
        server_name apitest.yhchmo.com;
        access_log /wwwlogs/apitest.log combined;
    
        location / {
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:9098/;
        }
    }
    
  • 监听443端口

    http {
        server {
            listen 443 ssl;
            server_name apitest.yhchmo.com;
            access_log /wwwlogs/apitest443.log combined;
    
            ssl on;
            ssl_certificate "/home/ssl/common/2581733_yhchmo.com.pem";
            ssl_certificate_key "/home/ssl/common/2581733_yhchmo.com.key";
    
            location / {
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass http://127.0.0.1:9098/;
            } 
    	}
    }
    

反向代理

http {
    upstream api-servers{
        server localhost:8081 weight=1;
        server localhost:8082 weight=3;
    }
    
    server {
       listen 80;
       server_name example.com;  # 替换为你的域名或IP
       access_log /var/log/nginx/access.log combined;
       location / {
           proxy_pass  http://api-servers;
           proxy_set_header  Host  $host:$server_port;
           proxy_set_header  X-Real-IP  $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}