插件窝 干货文章 nginx怎么搭建网站

nginx怎么搭建网站

Nginx sudo yourdomain 配置 90    来源:    2025-04-07

使用Nginx搭建网站的详细步骤

Nginx是一款高性能的HTTP和反向代理服务器,下面我将详细介绍如何使用Nginx搭建网站。

1. 安装Nginx

在Ubuntu/Debian系统上安装

sudo apt update
sudo apt install nginx

在CentOS/RHEL系统上安装

sudo yum install epel-release
sudo yum install nginx

2. 启动Nginx服务

sudo systemctl start nginx
sudo systemctl enable nginx  # 设置开机自启

3. 检查Nginx状态

sudo systemctl status nginx

4. 配置网站

4.1 默认网站配置

Nginx的默认配置文件位于: - Ubuntu/Debian: /etc/nginx/sites-available/default - CentOS/RHEL: /etc/nginx/conf.d/default.conf

4.2 创建新的网站配置

建议为每个网站创建单独的配置文件:

  1. 创建配置文件:
sudo nano /etc/nginx/sites-available/yourdomain.com
  1. 基本配置示例:
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;
    }
}

4.3 启用网站配置

创建符号链接到sites-enabled目录:

sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/

5. 创建网站目录和测试页面

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

6. 测试Nginx配置

sudo nginx -t

如果没有错误,重新加载Nginx:

sudo systemctl reload nginx

7. 防火墙设置

如果启用了防火墙,需要允许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

8. 访问网站

在浏览器中输入服务器IP地址或域名,应该能看到测试页面。

9. 进阶配置

9.1 配置HTTPS(SSL/TLS)

可以使用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

9.2 PHP支持

如果需要运行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;
}

9.3 反向代理配置

如果要代理到其他应用服务器:

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;
}

10. 日志查看

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搭建网站的基本步骤,根据实际需求可以进行更多定制化配置。