一、安装nginx
-
ubuntu1804当前apt源是1.14版本的,查看方法
sudo apt-cahce show nginx
-
nginx官网当下最新的文档版本是1.16了,所以我们需要为apt添加最新的安装源。
-
第一步,准备相关依赖包
sudo apt install curl gnupg2 ca-certificates lsb-release
-
第二步,在apt的安装源中(仓库)添加nginx的最新的稳定版(stable)的安装包
echo "deb [arch=amd64] http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
| sudo tee /etc/apt/sources.list.d/nginx.list
-
第三步,添加nginx的安装源的签名密钥,通过apt的安全认证
sudo curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add -
-
第四步,确认签名密钥
sudo apt-key fingerprint ABF5BD827BD9BF62 #如果返回以下信息,说明安装正确
pub rsa2048 2011-08-19 [SC] [expires: 2024-06-14]
573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62
uid [ unknown] nginx signing key <[email protected]>
-
第五步,执行安装命令
sudo apt update
sudo apt install nginx
-
apt update 更新提示错误,N: Skipping acquire of configured file 'nginx/binary-i386/Packages' as repository 'http://nginx.org/packages/ubuntu bionic InRelease' doesn't support architecture 'i386'
-
解决办法:vim /etc/apt/sources.list.d/nginx.list, 修改为:deb [arch=amd64] http://nginx.org/packages/ubuntu/ bionic nginx 增加 [arch=amd64]
-
apt 指定安装版本
-
apt-cache madison nginx 查询出版本
-
apt insatll nginx=Version 安装指定版本的nginx
二、启动nginx和nginx常用命令
-
启动/关闭/重启
sudo /etc/init.d/nginx start/down/restart
-
nginx优势:支持热部署,即可以不中断服务的同时,修改服务器配置信息
nginx -t
nginx -s reload
-
nginx常用命令
nginx -s quit 优雅停止nginx,有连接时会等连接请求完成再杀死worker进程
nginx -s reload 优雅重启,并重新载入配置文件nginx.conf
nginx -s reopen 重新打开日志文件,一般用于切割日志
nginx -v 查看版本
nginx -t 检查nginx的配置文件
nginx -h 查看帮助信息
nginx -V 详细版本信息,包括编译参数
nginx -c filename 指定配置文件
三、nginx的配置
-
配置文件位置.
-
主配置文件/etc/nginx/nginx.conf
-
应用配置文件夹, /etc/nginx/conf.d/ 此文件夹下.conf文件都会被载入
-
查看default.conf文件
cat /etc/nginx/conf.d/default.conf
server_name localhost
-
新建一个自己的静态网站配置
cd /etc/nginx/conf.d/
sudo cp default.conf mysite.conf
vim mysite.conf
sudo nginx -t #检查我们新建的配置文件是否正确
sudo nginx -s reload #重新加载配置文件
-
解决403的错误。
-
这个时候,直接访问www.mysite.com,容易出现是403错误,访问被禁止 forbidden
-
两个原因,一个是没有index.html文件(好解决,vim index.html到目录下),
-
一个是目录没有访问权限。我们可以设置/data/www/mysite的权限为755
-
nginx安装后,会默认增加nginx的用户和组,ch
sudo chmod 755 /data
sudo chmod 755 /data/www
sudo chmod 755 /data/www/mystie
#为什么要从/data开始,因为nginx的网站目录的权限,要求父目录及以上都拥有同样的权限,需要读和执行的权限
cat /etc/passwd #查看所有用户
cat /etc/group #查看所有组
chown -R nginx /data/www/mysite
chgrp -R nginx /data/www/mysite
-
配置https
-
前提需要您有你自己域名的ssl认证。个人可以申请一个免费的,网上有资源,自己百度以下
-
将证书文件传到服务器,使用的是scp命令将证书拷贝到服务器的/etc/nginx/ssl_certs/目录下面。现在该目录下有两个文件,xxx.pem 和 xxx.key。
-
在创建配置文件/etc/nginx/conf.d/目录下创建 myhttps.conf
server {
listen 443 ssl;
server_name www.mysite.com;
ssl_certificate /etc/nginx/ssl_certs/xxx.pem;
ssl_certificate_key /etc/nginx/ssl_certs/xxx.key;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root /data/www/mysite;
index index.html index.htm;
}
}
server {
listen 80;
server_name wwww.mysite.com;
rewrite ^(.*) https://$server_name$1 permanent;
}
sudo nginx -t
sudo nginx -s reload