Nginx
优质
小牛编辑
133浏览
2023-12-01
Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。
目录结构
/etc/nginx/nginx.conf
: 全局配置文件,用来配置 Nginx、配置端口等/etc/nginx/conf.d/
: 附加配置目录,用来对 Nginx 模块和模块化配置/etc/nginx/vhost/
: 虚拟主机配置目录,用来配置虚拟主机创建网站/var/log/nginx/
: 日志目录,包含 Nginx 错误日志以及虚拟主机访问日志和错误日志/var/www/
: 站点默认目录
服务管理
systemctl start nginx # 启动 nginx
systemctl restart nginx # 重启 nginx
systemctl stop nginx # 停止 nginx
systemctl status nginx # 查看 nginx 服务状态
Nginx 创建站点/虚拟主机
- 在
/etc/nginx/vhost/
目录下新建后缀为.conf
虚拟主机配置文件,内容如下:server { listen 80; # listen 监听端口,默认80,保持默认即可 server_name www.example.com; # server_name 域名,支持多个域名。用空格间隔 root /var/www/example; # root 网站根目录 error_log /var/log/nginx/example-error.log crit; # error_log 错误日志(可选) access_log /var/log/nginx/example-access.log; # access_log 访问日志(可选) index index.php index.html; # index 文档首页 # PHP 支持(可选) location ~ .*\.php$ { fastcgi_pass php-fpm; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; try_files $uri = 404; } # PHP 支持 include phpmyadmin.conf; # 站点需要支持 phpmyadmin 数据库管理请添加这条(可选) }
- 重启 Nginx 服务
Nginx 配置域名
- 在虚拟主机配置目录下找到默认创建的虚拟主机配置文件(例如:example.conf)
- 编辑虚拟主机配置文件
- 找到并修改
server_name
server_name www.example.com # server_name 主域名/主机地址
- 重启 Nginx 服务
Nginx 配置SSL证书
上传或下载证书到 SSL 证书目录
/var/lib/ssl
在新建的虚拟主机配置文件内添加,并做对应的修改:
server { listen 443 ssl; server_name www.example.com; root /var/www/example; index index.php index.html; ssl_certificate /var/lib/ssl/www.example.com.pem; ssl_certificate_key /var/lib/ssl/www.example.com.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; # PHP 支持 location ~ .*\.php$ { fastcgi_pass php-fpm; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; try_files $uri = 404; } }
server { listen 443 ssl; server_name www.example.com; root /var/www/example; index index.php index.html; ssl_certificate /var/lib/ssl/www.example.com.pem; ssl_certificate_key /var/lib/ssl/www.example.com.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; # PHP 支持 location ~ .*\.php$ { fastcgi_pass php-fpm; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; try_files $uri = 404; } include phpmyadmin.conf; # 站点需要支持 phpmyadmin 数据库管理 } # HTTPS 跳转 server { listen 80; server_name www.example.com; rewrite ^/(.*)$ https://www.example.com/$1 permanent; }