# nginx


## 安装

两种安装方式

+   下载 nginx.rpm 包并安装

    ```sh
    # 下载
    http://nginx.org/packages/rhel/7/x86_64/RPMS/
    # 安装
    yum install nginx.rpm
    ```

    

+   直接使用 yum 安装

    ```sh
    # 检查本机 yum 仓库是否包含 nginx
    yum info nginx
    # 如果仓库没有 nginx, 安装 EPEL 仓库
    # 适用于 centos7, 其他系统可查看文档 https://developer.aliyun.com/mirror/epel
    wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
    # 安装 nginx
    yum install -y nginx
    ```



## Nginx 的配置文件和最佳实践

- `yum install -y nginx`
- 通过以上方式安装的 Nginx，所有相关的配置文件都在 `/etc/nginx/` 目录中。
- Nginx 的主配置文件是 **/etc/nginx/nginx.conf**。
- 为了使 Nginx 配置更易于维护，建议为每个服务（域名）创建一个单独的配置文件。
- 每一个独立的 Nginx 服务配置文件都必须以 `.conf `结尾，并存储在 **/etc/nginx/conf.d** 目录中。您可以根据需求，创建任意多个独立的配置文件。
- 独立的配置文件，建议遵循以下命名约定，比如你的域名是 `kaifazhinan.com`，那么你的配置文件的应该是这样的 `/etc/nginx/conf.d/kaifazhinan.com.conf`，如果你在一个服务器中部署多个服务，当然你也可以在文件名中加上 Nginx 转发的端口号，比如 `kaifazhinan.com.3000.conf`，这样做看起来会更加友好。
- 如果你的配置中有很多重复的代码，那么建议你创建一个 `/etc/nginx/snippets` 文件夹，在这里面存放所有会被复用的代码块，然后在各个需要用到的 Nginx 的配置文件中引用进去，这样可以更方便管理和修改。
- Nginx 日志文件（`access.log` 和 `error.log` ）位于 **/var/log/nginx/** 目录中。建议为每个独立的服务配置不同的访问权限和错误日志文件，这样查找错误时，会更加方便快捷。
- SSL 证书文件位于 **/etc/pki/nginx** 目录中。
- 你可以将要部署的代码文件，存储在任何你想的位置，但是一般推荐存放在下列位置中的其中一个：
    - `/home/`
    - `/var/www/`
    - `/var/www/html/`
    - `/opt/`
    - `/usr/share/nginx/html`



## 启动和停止

两种启动方式

+   `nginx start` 对应停止方式 `nginx -s stop` 或者 `kill -s [signal] [nginx_pid]`

    +   `kill -s QUIT [nginx_pid]` 用于快速强制停止 nginx, 可能会丢失部分信息
    +   `kill -s TERM [nginx_pid]` 用于平缓停止 nginx,会等待工作进程将请求结束以后再停止

+   `systemctl start nginx` 对应停止方式 `systemctl stop nginx`

    通过 systemctl start nginx 启动的nginx 最好通过 systemctl stop nginx 来停止



## 常用命令

```sh
# 启动
systemctl start nginx
# 停止
systemctl stop nginx
# 开机启动
systemctl enable nginx
# 测试配置 
nginx -t
# 重新加载配置
systemctl reload nginx
```



## conf

`vim /etc/nginx/nginx.conf`

##### 监听特定域名

```nginx
server {
    listen       443 ssl http2;
    server_name  example.com;
}
```

##### 获取远端真实 IP

```nginx
location / {
    # 获取 remote real IP
	proxy_set_header Host $host;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}
```

##### http 重定向 https

```nginx
server {
    listen      80;
    server_name _;
    return 301 https://$host$request_uri;
}
```

##### websocket

```nginx
location / {
    proxy_pass http://localhost:80;
}

location /websocket {
    proxy_pass http://localhost:80;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
}
```




