在部署一个网站的时候,可能需要更改Nginx的配置,然后重启Nginx服务,部署的网站才能够访问。
在这里先简单总结一下nginx部署网站的步骤吧。

nginx建站流程简介

  • 安装Nginx。以下说明步骤中都使用相对路径,具体部署时将.替换为nginx安装所在路径即可。
  • 到./nginx/sites-available/下面创建你的网站的配置文件homepage.com,内容为:
server{
    listen  port1; #你的网站程序里使用的端口号
    server_name nginx所在服务器的ip;
    location / {
        # Pass the request to Gunicorn
        proxy_pass http://127.0.0.1:port2; #网站端口号
        proxy_read_timeout 6000;
        proxy_set_header Host $host: port1;
        proxy_set_header X-Real-IP $remote_addr; #你的网站程序里使用的端口号
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
  • 将homepage.com软连接到./nginx/sites-enabled/下面。注意要使用绝对路径(假设nginx安装在/etc目录):

ln -s /etc/nginx/sites-available/homepage.com /etc/nginx/sites-enabled/homepage.com

  • 开放防火墙相关端口(这里是上面的配置文件里的port2)

iptables -I INPUT -p tcp --dport port2 -j ACCEPT

  • 启动你的网站(视你使用的网站开发工具而定)

nohup python -m my_server &

  • 重启nginx服务

systemctl restart nginx

至此,理论上你的网站已经搭建好了,可以访问了。但是你可能会遇到一些问题,
下面就是本文的重点:

可能遇到的问题:

1、重启nginx失败,你可能会得到下面一条错误信息:

Job for nginx.service failed because the control process exited with error code. Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journal
那么你可以按照提示去看看到底是什么错误。
但根据我的经验,启动失败很大概率原因是配置文件有问题。
重点来了,你还可以通过这条命令去校验你的Nginx配置是否成功:
nginx -t
如果成功,他会给出如下信息:

# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

如果你的配置文件有问题,也能从错误信息中看出来:

a duplicate default server for [::]:80 in /etc/nginx/nginx.conf:41

错误已经很明显了,有多个配置文件里面使用了80端口。所以你可以用下面这条命令去查找一下:

grep -R default_server /etc/nginx
# 啰嗦一句,-R的意思是递归查找。这条命令会从 /etc/nginx下递归查找所有包含 default_server 的文件

找到该文件,写个别的端口或者删掉没用的文件,这个错误就可以解决了!

 

2、查看Nginx服务状态你可以发现:

# systemctl status nginx.service
	● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since 2018-11-06 12:31:21 JST; 15s ago
...
11月 06 12:31:20 zhangch-101 nginx[1863]: nginx: [emerg] bind() to 0.0.0.0:5001 failed (98: Address already in use)
11月 06 12:31:21 zhangch-101 systemd[1]: nginx.service: control process exited, code=exited status=1
11月 06 12:31:21 zhangch-101 nginx[1863]: nginx: [emerg] still could not bind()
11月 06 12:31:21 zhangch-101 systemd[1]: Failed to start The nginx HTTP and reverse proxy server.
11月 06 12:31:21 zhangch-101 systemd[1]: Unit nginx.service entered failed state.
11月 06 12:31:21 zhangch-101 systemd[1]: nginx.service failed.

这个错误比较明显,已经有进程占用这个端口了。
这时你就应该去看看哪个进程占用了这个端口:
netstat -nap | grep 5001
但是根据我的经验,应该是你的网站配置文件把你的网站的本地端口和nginx端口写反了。
也就是说把上面的nginx建站流程中第2步的port1,port2换一下,重启服务,这个问题应该就解决了。
 

3、没有sites-available文件
自己在/etc/nginx/下创建一下就行。
但是别忘了在/etc/nginx/nginx.conf中找到http {},在里面加上一句:

include /etc/nginx/sites-enabled/*;