Nginx配置指南
一、Nginx配置文件详解
Nginx(engine x)是一款高性能的Web服务器,可以作为反向代理、负载均衡器和HTTP缓存等多种用途。在使用Nginx时,需要编辑其配置文件(nginx.conf)来指定如何处理传入的请求。Nginx配置文件包含多个块(block),每个块内部包含多个指令(directive)。以下是一个简单的Nginx配置文件示例:
worker_processes 1;
error_log logs/error.log;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.html;
}
}
二、Nginx配置证书和域名
对于需要使用SSL(Secure Sockets Layer)协议的网站,需要在Nginx配置文件中指定证书和域名。证书一般由证书授权机构(CA)颁发,包含公钥和私钥两部分文件。其中,公钥会发布到互联网上,私钥保密保存。以下是一个Nginx配置SSL证书的示例:
http {
...
server {
listen 443 ssl;
server_name example.com;
root /var/www/example.com;
index index.html;
ssl_certificate /etc/nginx/cert/example.com.crt;
ssl_certificate_key /etc/nginx/cert/example.com.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL;
location / {
...
}
}
}
上述配置中,ssl_certificate
指定证书文件的路径,ssl_certificate_key
指定私钥文件的路径。ssl_session_timeout
指定SSL会话的超时时间,ssl_protocols
指定支持的SSL协议版本,ssl_ciphers
指定使用的加密算法。
三、Nginx配置PEM证书
PEM(Privacy Enhanced Mail)证书是一种常见的证书格式,可以包含公钥和私钥,并且基于文本格式。以下是一个Nginx配置PEM证书的示例:
http {
...
server {
listen 443 ssl;
server_name example.com;
root /var/www/example.com;
index index.html;
ssl_certificate /etc/nginx/cert/example.com.pem;
ssl_certificate_key /etc/nginx/cert/example.com.pem;
location / {
...
}
}
}
四、Nginx安装配置SSL证书
安装SSL证书时,需要先生成证书请求文件(CSR,Certificate Signing Request),然后将该文件提交给证书授权机构颁发证书。在得到证书文件后,可以配置到Nginx中使用。以下是一个安装SSL证书的示例:
# 生成CSR文件
openssl req -new -newkey rsa:2048 -nodes -keyout example.com.key -out example.com.csr
# 将CSR文件提交给CA机构颁发证书
# ...
# 将证书和私钥文件保存到/etc/nginx/cert目录下
# ...
# 修改Nginx配置文件
http {
...
server {
listen 443 ssl;
server_name example.com;
root /var/www/example.com;
index index.html;
ssl_certificate /etc/nginx/cert/example.com.crt;
ssl_certificate_key /etc/nginx/cert/example.com.key;
location / {
...
}
}
}
五、查看Nginx配置
可以通过执行命令nginx -t
来检查Nginx配置文件的语法是否正确。如果输出为“syntax is ok”,则表示配置无误。如果配置有误,则会输出错误信息。以下是一个示例:
$ nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful