Nginx反向代理和多站点配置实现及问题解决


Nginx是一款轻量级Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。

Nginx 是一个很强大的高性能 Web反向代理服务器,它具有很多非常优越的特性:
在高连接并发的情况下,Nginx是 Apache服务器不错的替代品:Nginx在美国是做虚拟主机生意的老板们经常选择的软件平台之一。能够支持高达 50,000 个并发连接数的响应,感谢Nginx为我们选择了 epoll and kqueue作为开发模型。

Nginx作为负载均衡服务器:Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务,也可以支持作为 HTTP代理服务器对外进行服务。Nginx采用C进行编写,不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多。


-----------------------------Nginx反向代理的配置----------------------------

Nginx 作为 web 服务器一个重要的功能就是反向代理。其实我们在前面的一篇文章《Nginx多站点配置的一次实践》里,用的就是 Nginx 的反向代理,这里简单再提一下。

下面是配置 Nginx 作为 tornado 的反向代理的设置:

01 upstream tornado {
02     server 127.0.0.1:8888;
03 }
04   
05 server {
06     listen   80;
07     root /root/nmapp2_venv;
08     index index.py index.html;
09   
10     server_name server;
11   
12     location / {
13         #if (!-e $request_filename) {
14         #    rewrite ^/(.*)$ /index.py/$1 last;
15         #}
16     }
17   
18     location ~ /index\.py {
19         proxy_pass_header Server;
20         proxy_set_header Host $http_host;
21         proxy_set_header X-Real-IP $remote_addr;
22         proxy_set_header X-Scheme $scheme;
23         proxy_pass http://tornado;
24     }
25 }

Nginx 反向代理的指令不需要新增额外的模块,默认自带 proxy_pass 指令,只需要修改配置文件就可以实现反向代理。

再举一个例子吧。比如要配置后端跑 apache 服务的 ip 和端口,也就是说,我们的目标是实现通过 http://ip:port 能访问到你的网站。

只要新建一个 vhost.conf,加入如下内容(记得修改 ip 和域名为你的 ip 和域名)。修改nginx.conf,添加 include quancha.conf 到http{}段, reload nginx就可以了。

Nginx 反向代理模板:

01 ## Basic reverse proxy server ##
02 upstream apachephp  {
03     server ip:8080; #Apache
04 }
05   
06 ## Start www.nowamagic.net ##
07 server {
08     listen 80;
09     server_name  www.nowamagic.net;
10   
11     access_log  logs/quancha.access.log  main;
12     error_log  logs/quancha.error.log;
13     root   html;
14     index  index.html index.htm index.php;
15   
16     ## send request back to apache ##
17     location / {
18         proxy_pass  http://apachephp;
19   
20         #Proxy Settings
21         proxy_redirect     off;
22         proxy_set_header   Host             $host;
23         proxy_set_header   X-Real-IP        $remote_addr;
24         proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
25         proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
26         proxy_max_temp_file_size 0;
27         proxy_connect_timeout      90;
28         proxy_send_timeout         90;
29         proxy_read_timeout         90;
30         proxy_buffer_size          4k;
31         proxy_buffers              4 32k;
32         proxy_busy_buffers_size    64k;
33         proxy_temp_file_write_size 64k;
34    }
35 }

这就完成了 Nginx 反向代理配置。

-------------------------- Nginx多站点配置-------------------------

在一台 VPS 上,我们有时候需要同时跑几个 virtualenv。比如 virtualenv app1 跑的是 Django 的一个应用,而 virtualenv app2 跑的是 Tornado。那么如何配置 Nginx,让它同时支持这两个 virtualenv 的运行呢?

首先是 Nginx 的主配置,位于 etc/nginx/ngnix.conf,让它保持默认就行:

01 user  nginx;
02 worker_processes  1;
03  
04 error_log  /var/log/nginx/error.log warn;
05 pid        /var/run/nginx.pid;
06  
07  
08 events {
09     worker_connections  1024;
10 }
11  
12  
13 http {
14     include       /etc/nginx/mime.types;
15     default_type  application/octet-stream;
16  
17     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
18                       '$status $body_bytes_sent "$http_referer" '
19                       '"$http_user_agent" "$http_x_forwarded_for"';
20  
21     access_log  /var/log/nginx/access.log  main;
22  
23     sendfile        on;
24     #tcp_nopush     on;
25  
26     keepalive_timeout  65;
27  
28     #gzip  on;
29  
30     server {
31         listen       80;
32         server_name  112.124.7.216;
33         #server_name localhost;
34         #if ($host != 'www.nowamagic.net' ) {
35         #    rewrite ^/(.*)$ http://www.nowamagic.net/$1 permanent;
36         #}
37  
38         access_log /home/nowamagic/logs/access.log;
39         error_log /home/nowamagic/logs/error.log;
40  
41         #root         /root/nowamagic_venv/nowamagic_pj;
42         location / {
43             uwsgi_pass 127.0.0.1:8077;
44             #include uwsgi_params;
45             include /etc/nginx/uwsgi_params;
46             #uwsgi_pass 127.0.0.1:8077;
47             #uwsgi_param UWSGI_SCRIPT index;
48             #uwsgi_param UWSGI_PYHOME $document_root;
49             #uwsgi_param UWSGI_CHDIR  $document_root;
50        }
51  
52        location ~ \.php$ { 
53            #root          html; 
54            root           /var/www/html;
55            fastcgi_pass   127.0.0.1:9000; 
56            fastcgi_index  index.php; 
57            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name; 
58            include        fastcgi_params; 
59        }
60  
61        access_log off;
62     }
63  
64  
65     include /etc/nginx/conf.d/*.conf;
66 }

注意到这一句,include /etc/nginx/conf.d/*.conf; 它会加载 conf.d 文件夹下的所有配置文件。那么接下来的事情就简单了,我们设计两个 .conf ,一个是 django 的配置,一个是 tornado 的配置。

1. app1_django.conf

01 server {
02     listen       80;
03     server_name  112.124.7.216;
04     #server_name localhost;
05     #if ($host != 'www.imofa.net' ) {
06     #    rewrite ^/(.*)$ http://www.imofa.net/$1 permanent;
07     #}
08  
09     access_log /home/nowamagic/logs/access.log;
10     error_log /home/nowamagic/logs/error.log;
11  
12     #root         /root/nowamagic_venv/nowamagic_pj;
13     location / {
14         uwsgi_pass 127.0.0.1:8077;
15         #include uwsgi_params;
16         include /etc/nginx/uwsgi_params;
17         #uwsgi_pass 127.0.0.1:8077;
18         #uwsgi_param UWSGI_SCRIPT index;
19         #uwsgi_param UWSGI_PYHOME $document_root;
20         #uwsgi_param UWSGI_CHDIR  $document_root;
21    }
22  
23    location ~ \.php$ { 
24        #root          html; 
25        root           /var/www/html;
26        fastcgi_pass   127.0.0.1:9000; 
27        fastcgi_index  index.php; 
28        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name; 
29        include        fastcgi_params; 
30    }
31  
32    access_log off;
33 }

下面是 tornado 的配置:

2. app2_tornado.conf

01 upstream tornado {
02     server 127.0.0.1:8888;
03 }
04   
05 server {
06     listen   80;
07     root /root/nmapp2_venv;
08     index index.py index.html;
09   
10     server_name server;
11   
12     location / {
13         #if (!-e $request_filename) {
14         #    rewrite ^/(.*)$ /index.py/$1 last;
15         #}
16     }
17   
18     location ~ /index\.py {
19         proxy_pass_header Server;
20         proxy_set_header Host $http_host;
21         proxy_set_header X-Real-IP $remote_addr;
22         proxy_set_header X-Scheme $scheme;
23         proxy_pass http://tornado;
24     }
25 }

重启 Nginx:

1 service nginx restart

OK,两个虚拟环境的 app 都能访问了。

    ---------------配置过程中遇到的问题及解决方法-----------------

  问题一: 

   有时候修改nginx配置文件nginx.conf后需要reload下,操作不当可能会报如下错误:

    [root@localhost sbin]# ./nginx -s reload
    nginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)
 
   解决方法:
    [root@localhost nginx]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
 
   使用nginx -c的参数指定nginx.conf文件的位置
 
   [root@localhost nginx]# cd logs/
   [root@localhost logs]# ll
  总用量 12
-rw-r--r-- 1 root root 1246 12月  9 18:10 access.log
-rw-r--r-- 1 root root  516 12月 10 15:39 error.log
-rw-r--r-- 1 root root    5 12月 10 15:38 nginx.pid
 
   看nginx.pid文件已经有了。

问题二:

   有时候反向代理的域名和负载如果配置不对应,就会报下面的错误:

   nginx: [emerg] host not found in upstream "sns.onbobo.local" in /etc/nginx/nginx.conf:87

   解决见下图:

  


问题三:

   如果tomcat用nginx做了代理,在nginx启动状态时stop tomcat会报如下错误:

   PID file found but no matching process was found. Stop aborted.

   解决办法:需要先stop nginx,然后再stop tomcat才可以,nginx具体使用命令见下面的"nginx常用管理命令"


--------------nginx常用管理命令-----------------

几个常用的nginx命令


Nginx 安装后只有一个程序文件,本身并不提供各种管理程序,它是使用参数和系统信号机制对 Nginx 进程本身进行控制的。 Nginx 的参数包括有如下几个:

可以这样使用

/usr/local/nginx/sbin/nginx -参数

-c :使用指定的配置文件而不是 conf 目录下的 nginx.conf 。

-t:测试配置文件是否正确,在运行时需要重新加载配置的时候,此命令非常重要,用来检测所修改的配置文件是否有语法错误。

-s reload 重载

-s stop 停止

nginx启动/重启/停止

这个很简单,就是运行命令:

sudo /etc/init.d/nginx {start|restart|stop}

nginx检查配置

/usr/local/nginx/sbin/nginx -t nginx.conf

nginx修改配置后重载

/usr/local/nginx/sbin/nginx -s reload

### 宝塔面板中 Nginx 的使用与配置教程 #### 一、Nginx 自定义 404 页面配置 在宝塔面板中,可以通过自定义 `nginx.conf` 文件实现 404 错误页面的设置。具体操作如下: 1. 登录到宝塔面板并进入网站管理界面。 2. 找到目标站点,点击“设置”按钮,在弹出菜单中选择“配置文件”选项卡。 3. 编辑该站点的 Nginx 配置文件,添加以下代码片段以指定 404 页面路径: ```nginx error_page 404 /custom_404.html; location = /custom_404.html { root /www/wwwroot/yourdomain.com/; } ``` 上述代码表示当发生 404 错误时返回 `/custom_404.html` 页面[^1]。 4. 修改完成后保存配置,并通过命令行验证 Nginx 配置文件的有效性: ```bash /opt/nginx/sbin/nginx -t ``` --- #### 二、Nginx 反向代理 WebSocket (WSS) 配置 为了支持 WebSocket 协议(尤其是加密版本 WSS),需要调整 Nginx 中的反向代理规则。以下是具体的配置方式: 1. 进入宝塔面板的目标站点配置文件编辑器。 2. 添加或修改以下内容至服务器块内: ```nginx map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name yourdomain.com; location /ws/ { proxy_pass http://backend_server_address; # 替换为目标地址 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } ``` 此处的关键在于 `proxy_set_header` `$connection_upgrade` 映射逻辑[^2]。 3. 测试配置有效性后重新加载服务即可生效。 --- #### 三、Windows 环境下手动配置 PHP-Nginx 环境 对于 Windows 用户而言,虽然官方推荐 Linux 平台作为生产环境首选方案,但在开发阶段仍可尝试搭建本地测试环境。以下是基于宝塔面板的手动配置流程概述: 1. 创建一个新的虚拟主机目录结构; 2. 将 PHP-FPM 设置为 FastCGI 接口监听模式; 3. 更新 Nginx配置文件加入类似以下条目: ```nginx fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_index index.php; fastcgi_pass 127.0.0.1:9000; ``` 更多细节参见参考资料[^3]。 --- #### 四、Docker+Nginx+Gunicorn 部署 Django 应用实例 如果计划利用 Docker 技术简化运维工作流,则可以参考此部分说明完成 Django Web 应用程序上线准备过程: 1. 构建镜像前需先确认依赖项已妥善处理完毕,例如运行数据库迁移脚本以及收集静态资源等任务: ```bash python manage.py migrate python manage.py collectstatic --noinput ``` 2. Gunicorn 是一种高性能 Python HTTP Server 工具,适合用来承载大型流量场景下的 API 请求负载均衡需求;而 Nginx 则主要负责前端访问入口转发功能[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值