Ubuntu(18.04)安装Nginx并配置

安装Nginx

1
2
sudo apt update
sudo apt install nginx

如果能看到版本号,说明安装成功:

1
2
nginx -v
// nginx version: nginx/1.14.0 (Ubuntu)

查看状态

1
2
3
4
5
6
7
8
9
10
11
12
systemctl status nginx

// 输出
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2018-04-20 16:08:19 UTC; 3 days ago
Docs: man:nginx(8)
Main PID: 2369 (nginx)
Tasks: 2 (limit: 1153)
CGroup: /system.slice/nginx.service
├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
└─2380 nginx: worker process

看到running说明已经启动成功了,再来通过ip访问下看看:

2216

nginx常用的几个命令

关闭

1
sudo systemctl stop nginx

开启

1
sudo systemctl start nginx

重启

1
sudo systemctl restart nginx

重载配置文件,一般用不关闭nginx更新配置

1
sudo systemctl reload nginx

开机自启

1
sudo systemctl enable nginx

关闭开机自启

1
sudo systemctl disable nginx

配置一个站点

1. 首先,把我们的站点创建在/var/www/example.com目录下:

1
sudo mkdir -p /var/www/example.com

2. 设置目录的权限

1
2
sudo chown -R $USER:$USER /var/www/example.com
sudo chmod -R 755 /var/www/example.com

3. 创建index.html

1
vim /var/www/example.com/index.html

内容如下:

1
2
3
4
5
<html>
<body>
<h1>Hello World!</h1>
</body>
</html>

4. 修改nginx

1
sudo vim /etc/nginx/sites-available/example.com

内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80;
listen [::]:80;

root /var/www/example.com;
index index.html index.htm;

server_name example.com www.example.com;

location / {
try_files $uri $uri/ =404;
}
}

创建软连接到sites-enable目录:

1
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

5. 检查nginx配置

1
2
3
4
sudo nginx -t

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

没有问题的话,就可以重启nginx了:

1
sudo systemctl restart nginx