ITPub博客

首页 > 应用开发 > IT综合 > Linux Web服务器搭建指南:从零部署到配置优化

Linux Web服务器搭建指南:从零部署到配置优化

投稿 IT综合 作者:bhluo 时间:2025-12-23 16:28:39 0 删除 编辑

# Linux Web服务器搭建指南:从零部署到配置优化


## 环境准备与系统配置


在开始搭建Web服务器之前,需要确保Linux系统已经正确安装并更新。以下以Ubuntu 22.04 LTS为例,其他发行版的命令略有不同:


```bash

# 更新系统软件包

sudo apt update

sudo apt upgrade -y


# 设置主机名(可选)

sudo hostnamectl set-hostname webserver


# 配置防火墙(如果启用)

sudo ufw allow 22/tcp        # 开放SSH端口

sudo ufw allow 80/tcp        # 开放HTTP端口

sudo ufw allow 443/tcp       # 开放HTTPS端口

sudo ufw enable              # 启用防火墙


# 查看网络配置

ip addr show                 # 显示IP地址

hostname -I                  # 显示所有IP地址

```


对于时间同步,确保系统时间准确:

```bash

# 安装并配置NTP服务

sudo apt install chrony -y

sudo systemctl enable chrony

sudo systemctl start chrony

sudo chronyc sources         # 检查时间同步状态

```


## Web服务器选择与安装


常见的Web服务器有Nginx、Apache等,这里以Nginx为例,因其性能优秀且配置简单:


```bash

# 安装Nginx

sudo apt install nginx -y


# 检查安装是否成功

nginx -v                     # 显示版本信息


# 启动Nginx服务

sudo systemctl start nginx

sudo systemctl enable nginx  # 设置开机自启


# 检查服务状态

sudo systemctl status nginx


# 测试Web服务器

curl http://localhost        # 应该看到欢迎页面

```


如果选择Apache服务器,安装命令如下:

```bash

# 安装Apache

sudo apt install apache2 -y


# 管理Apache服务

sudo systemctl start apache2

sudo systemctl enable apache2

sudo systemctl status apache2

```


## 基础配置与虚拟主机设置


创建网站目录并设置权限:

```bash

# 创建网站根目录

sudo mkdir -p /var/www/example.com/html

sudo mkdir -p /var/www/example.com/logs


# 设置目录权限

sudo chown -R $USER:$USER /var/www/example.com/html

sudo chmod -R 755 /var/www


# 创建测试页面

cat > /var/www/example.com/html/index.html << EOF

<!DOCTYPE html>

<html>

<head>

    <title>欢迎访问我的网站</title>

</head>

<body>

    <h1>网站搭建成功!</h1>

    <p>服务器时间:<span id="datetime"></span></p>

    <script>

        document.getElementById('datetime').textContent = new Date();

    </script>

</body>

</html>

EOF

```


配置Nginx虚拟主机:

```bash

# 创建虚拟主机配置文件

sudo nano /etc/nginx/sites-available/example.com


# 文件内容如下:

server {

    listen 80;

    listen [::]:80;

    

    server_name example.com

    root /var/www/example.com/html;

    index index.html index.htm;

    

    access_log /var/www/example.com/logs/access.log;

    error_log /var/www/example.com/logs/error.log;

    

    location / {

        try_files $uri $uri/ =404;

    }

    

    # 静态文件缓存设置

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {

        expires 30d;

        add_header Cache-Control "public, immutable";

    }

}


# 启用虚拟主机

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


# 测试配置语法

sudo nginx -t


# 重新加载Nginx配置

sudo systemctl reload nginx

```


对于Apache服务器,配置略有不同:

```bash

# 创建Apache虚拟主机配置

sudo nano /etc/apache2/sites-available/example.com.conf


# 内容示例:

<VirtualHost *:80>

    ServerName example.com

    ServerAlias

    DocumentRoot /var/www/example.com/html

    

    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log

    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined

    

    <Directory /var/www/example.com/html>

        Options Indexes FollowSymLinks

        AllowOverride All

        Require all granted

    </Directory>

</VirtualHost>


# 启用站点并重载

sudo a2ensite example.com.conf

sudo a2dissite 000-default.conf

sudo systemctl reload apache2

```


## 数据库服务器安装与配置


对于动态网站,通常需要数据库支持。MySQL和PostgreSQL是常见选择:


```bash

# 安装MySQL

sudo apt install mysql-server -y


# 安全配置MySQL

sudo mysql_secure_installation


# 登录MySQL

sudo mysql


# 创建数据库和用户

CREATE DATABASE webapp;

CREATE USER 'webuser'@'localhost' IDENTIFIED BY 'strong_password';

GRANT ALL PRIVILEGES ON webapp.* TO 'webuser'@'localhost';

FLUSH PRIVILEGES;

EXIT;


# 或者选择PostgreSQL

sudo apt install postgresql postgresql-contrib -y


# 切换到postgres用户

sudo -i -u postgres


# 创建数据库和用户

createdb webapp

createuser --interactive

# 按照提示设置用户名和权限

```


## PHP安装与配置


如果需要运行PHP应用,需要安装PHP及相关扩展:


```bash

# 安装PHP和常用扩展

sudo apt install php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-zip -y


# 检查PHP版本

php --version


# 配置PHP-FPM

sudo nano /etc/php/8.1/fpm/php.ini

# 修改关键参数:

# memory_limit = 256M

# upload_max_filesize = 64M

# post_max_size = 64M


# 修改Nginx配置以支持PHP

sudo nano /etc/nginx/sites-available/example.com


# 在server块中添加:

location ~ \.php$ {

    include snippets/fastcgi-php.conf;

    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;

    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    include fastcgi_params;

<"xyz.ruihaihj.com"><"rat.ruihaihj.com"><"high.ruihaihj.com">

}


# 重启服务

sudo systemctl restart php8.1-fpm

sudo systemctl reload nginx


# 测试PHP

cat > /var/www/example.com/html/info.php << EOF

<?php

phpinfo();

?>

EOF

# 访问 http://your_server_ip/info.php 查看PHP信息

```


## SSL证书配置与HTTPS启用


使用Let's Encrypt免费证书启用HTTPS:


```bash

# 安装Certbot

sudo apt install certbot python3-certbot-nginx -y


# 获取并安装SSL证书

sudo certbot --nginx -d example.com -d

<"nit.ruihaihj.com"><"note.ruihaihj.com"><"ill.ruihaihj.com">


# 证书自动续期测试

sudo certbot renew --dry-run


# 查看自动续期配置

cat /etc/cron.d/certbot


# 手动配置SSL示例(如果需要自定义)

sudo nano /etc/nginx/sites-available/example.com


# 添加SSL配置:

server {

    listen 443 ssl http2;

    listen [::]:443 ssl http2;

    server_name example.com

    

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;

    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    

    # SSL优化设置

    ssl_protocols TLSv1.2 TLSv1.3;

    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;

    ssl_prefer_server_ciphers off;

    

    # HSTS头(强制HTTPS)

    add_header Strict-Transport-Security "max-age=63072000" always;

    

    # 其他配置...

}

```


## 性能优化与安全加固


优化Web服务器性能:


```bash

# 调整Nginx工作进程

sudo nano /etc/nginx/nginx.conf

# 修改:

# worker_processes auto;  # 根据CPU核心数自动设置

# worker_connections 1024; # 每个进程最大连接数


# 启用Gzip压缩

sudo nano /etc/nginx/nginx.conf

# 在http块中添加:

gzip on;

gzip_vary on;

gzip_min_length 1024;

gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;


# 配置浏览器缓存

sudo nano /etc/nginx/sites-available/example.com

# 在server块中添加:

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {

    expires 1y;

    add_header Cache-Control "public, immutable";

}

```


安全加固措施:


```bash

# 禁用Nginx版本信息

sudo nano /etc/nginx/nginx.conf

# 在http块中添加:

server_tokens off;


# 限制请求大小防止攻击

sudo nano /etc/nginx/nginx.conf

client_max_body_size 10m;

client_body_buffer_size 128k;


# 配置安全的HTTP头

add_header X-Frame-Options "SAMEORIGIN" always;

add_header X-Content-Type-Options "nosniff" always;

add_header X-XSS-Protection "1; mode=block" always;

add_header Referrer-Policy "strict-origin-when-cross-origin" always;


# 创建简单的防火墙规则

sudo apt install fail2ban -y

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

sudo nano /etc/fail2ban/jail.local

# 修改SSH相关配置

[sshd]

enabled = true

port = ssh

filter = sshd

logpath = /var/log/auth.log

maxretry = 3

bantime = 3600


sudo systemctl restart fail2ban

```


## 监控与维护脚本


创建简单的监控脚本:


```bash

# 创建网站状态检查脚本

cat > /usr/local/bin/check-website.sh << 'EOF'

#!/bin/bash

SITE="example.com"

LOG_FILE="/var/log/website-monitor.log"

STATUS=$(curl -o /dev/null -s -w "%{http_code}" "https://$SITE")


if [ "$STATUS" != "200" ]; then

    echo "$(date): 网站 $SITE 状态异常,HTTP代码: $STATUS" >> $LOG_FILE

    # 可以添加邮件通知或重启服务的逻辑

    # systemctl restart nginx

else

    echo "$(date): 网站 $SITE 运行正常" >> $LOG_FILE

fi

EOF


sudo chmod +x /usr/local/bin/check-website.sh


# 添加定时任务

sudo crontab -e

# 添加以下行:

*/5 * * * * /usr/local/bin/check-website.sh


# 日志轮转配置

sudo nano /etc/logrotate.d/nginx-custom

# 内容:

/var/www/example.com/logs/*.log {

    daily

    missingok

    rotate 14

    compress

    delaycompress

    notifempty

    create 0640 www-data adm

    sharedscripts

    postrotate

        systemctl reload nginx > /dev/null 2>&1 || true

    endscript

}

```


## 备份策略实施


设置定期备份:


```bash

# 创建备份脚本

cat > /usr/local/bin/backup-website.sh << 'EOF'

#!/bin/bash

BACKUP_DIR="/backup/websites"

DATE=$(date +%Y%m%d_%H%M%S)

SITE_DIR="/var/www/example.com"

DB_NAME="webapp"


# 创建备份目录

mkdir -p "$BACKUP_DIR"


# 备份网站文件

tar -czf "$BACKUP_DIR/example.com_files_$DATE.tar.gz" -C "$SITE_DIR" .


# 备份数据库

mysqldump -u webuser -p'strong_password' "$DB_NAME" > "$BACKUP_DIR/example.com_db_$DATE.sql"

gzip "$BACKUP_DIR/example.com_db_$DATE.sql"


# 删除7天前的备份

find "$BACKUP_DIR" -type f -mtime +7 -delete


echo "备份完成: $DATE"

EOF


sudo chmod +x /usr/local/bin/backup-website.sh


# 添加每日备份任务

sudo crontab -e

# 添加:

0 2 * * * /usr/local/bin/backup-website.sh

```


## 故障排查与常用命令


掌握基本的问题排查方法:


```bash

# 检查服务状态

sudo systemctl status nginx

sudo systemctl status mysql

sudo systemctl status php8.1-fpm


# 查看错误日志

sudo tail -f /var/log/nginx/error.log

sudo tail -f /var/www/example.com/logs/error.log


# 检查端口监听

sudo netstat -tulpn | grep :80

sudo netstat -tulpn | grep :443


# 测试网络连接

curl -I http://localhost

curl -I https://example.com


# 检查DNS解析

nslookup example.com

dig example.com


# 查看系统资源

top

htop

df -h              # 磁盘空间

free -h            # 内存使用

```


通过以上步骤,可以建立一个功能完整、安全可靠的Web服务器。关键是要根据实际需求调整配置,并建立良好的监控和维护习惯。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3106007/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2015-11-01

  • 博文量
    895
  • 访问量
    944941