Nginx是一款高性能的HTTP和反向代理服务器,下面我将详细介绍如何使用Nginx搭建网站。
sudo apt update
sudo apt install nginx
sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx # 设置开机自启
sudo systemctl status nginx
Nginx的默认配置文件位于:
- Ubuntu/Debian: /etc/nginx/sites-available/default
- CentOS/RHEL: /etc/nginx/conf.d/default.conf
建议为每个网站创建单独的配置文件:
sudo nano /etc/nginx/sites-available/yourdomain.com
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
root /var/www/yourdomain.com/html;
index index.html index.htm index.nginx-debian.html;
location / {
try_files $uri $uri/ =404;
}
}
创建符号链接到sites-enabled目录:
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
sudo mkdir -p /var/www/yourdomain.com/html
sudo chown -R $USER:$USER /var/www/yourdomain.com/html
sudo chmod -R 755 /var/www/yourdomain.com
# 创建测试页面
echo "<html><body><h1>Welcome to YourDomain.com!</h1></body></html>" > /var/www/yourdomain.com/html/index.html
sudo nginx -t
如果没有错误,重新加载Nginx:
sudo systemctl reload nginx
如果启用了防火墙,需要允许HTTP(80)和HTTPS(443)流量:
sudo ufw allow 'Nginx Full' # Ubuntu
# 或
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload # CentOS/RHEL
在浏览器中输入服务器IP地址或域名,应该能看到测试页面。
可以使用Let's Encrypt免费证书:
sudo apt install certbot python3-certbot-nginx # Ubuntu/Debian
sudo yum install certbot python3-certbot-nginx # CentOS/RHEL
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
如果需要运行PHP网站:
sudo apt install php-fpm # Ubuntu/Debian
sudo yum install php-fpm # CentOS/RHEL
然后在Nginx配置中添加:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
如果要代理到其他应用服务器:
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
Nginx日志通常位于:
- 访问日志: /var/log/nginx/access.log
- 错误日志: /var/log/nginx/error.log
查看日志命令:
sudo tail -f /var/log/nginx/error.log
sudo tail -f /var/log/nginx/access.log
以上是使用Nginx搭建网站的基本步骤,根据实际需求可以进行更多定制化配置。