Ubuntu部署nginX

通过APT安装nginx

sudo apt update
sudo apt upgrade
sudo apt install nginx

编辑nginx的配置文件

//nginx配置的主文件
sudo vim /etc/nginx/nginx.conf
//nginx.conf默认引用了/etc/nginx/conf.d/中的所有.conf文件,所以建议以在conf.d中添加文件的形式添加web服务配置
sudo vim /etc/nginx/conf.d/vm.conf

以基本的web服务为例,vm.conf的配置内容可以是:

server {

    # 使用的端口,及是否作为默认服务
    listen    16666 default_server;

    # 服务器名称,同一个IP的同一个端口可以设置为不同的域名,nginx可以根据用户访问的域名的不同      提供不同的网站服务。
    server_name yttj.f3322.net:16666;

    # 文件的位置
    location / {

        # 文件根目录
        root     /usr/share/nginx/html;

        # 主页文件名
        index    index.html;
    }
}

配置完成后,即可启动nginx

sudo systemctl start nginx
#启用开机自动启动
sudo systemctl enable nginx

Ubuntu的防火墙默认开启,还应设置防火墙开放服务的端口

sudo ufw allow 16666

WPSuperCache的Nginx配置

使用WPSuperCache必须令WordPress使用固定链接,而WordPress的固定链接在Nginx条件下必须修改nginx.conf(否则页面404),添加如下代码:

location / {
try_files $uri $uri/ /index.php?$args;
}

(而在Apache中则是一个名为rename的功能)。

systemctl配置脚本

vim /usr/lib/systemd/system/nginx.service
chmod +x /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecQuit=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start nginx.service