插件窝 干货文章 nginx自动化脚本怎么写

nginx自动化脚本怎么写

Nginx DOMAIN 配置 html 141    来源:    2025-04-21

Nginx自动化脚本编写指南

作为IT工程师,我可以为您提供几种常见的Nginx自动化脚本编写方法,包括安装、配置和管理等方面。

1. Bash脚本自动化安装Nginx

#!/bin/bash

# Nginx自动化安装脚本
# 适用于Ubuntu/Debian系统

# 更新系统包索引
sudo apt-get update

# 安装必要依赖
sudo apt-get install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring

# 导入官方Nginx签名密钥
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

# 验证密钥指纹
gpg --dry-run --quiet --no-keyring --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg

# 设置稳定版Nginx源
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

# 再次更新
sudo apt-get update

# 安装Nginx
sudo apt-get install -y nginx

# 启动Nginx服务
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

# 检查状态
sudo systemctl status nginx

echo "Nginx安装完成,访问 http://your_server_ip 查看默认页面"

2. 自动化配置Nginx虚拟主机

#!/bin/bash

# Nginx虚拟主机自动化配置脚本

# 参数检查
if [ "$#" -ne 2 ]; then
    echo "用法: $0 域名 根目录路径"
    exit 1
fi

DOMAIN=$1
ROOT_DIR=$2
CONFIG_FILE="/etc/nginx/conf.d/${DOMAIN}.conf"

# 创建网站根目录
sudo mkdir -p $ROOT_DIR
sudo chown -R $USER:$USER $ROOT_DIR
sudo chmod -R 755 $ROOT_DIR

# 创建示例index.html
echo "<html><head><title>Welcome to $DOMAIN</title></head><body><h1>Success! $DOMAIN is working!</h1></body></html>" > $ROOT_DIR/index.html

# 创建Nginx配置文件
sudo tee $CONFIG_FILE > /dev/null <<EOF
server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;

    root $ROOT_DIR;
    index index.html index.htm;

    location / {
        try_files \$uri \$uri/ =404;
    }

    access_log /var/log/nginx/$DOMAIN.access.log;
    error_log /var/log/nginx/$DOMAIN.error.log;
}
EOF

# 测试Nginx配置
sudo nginx -t

if [ $? -eq 0 ]; then
    # 重启Nginx使配置生效
    sudo systemctl restart nginx
    echo "虚拟主机 $DOMAIN 配置完成,网站根目录: $ROOT_DIR"
else
    echo "Nginx配置测试失败,请检查配置"
    exit 1
fi

3. 使用Ansible自动化部署Nginx

---
# nginx_playbook.yml
- name: Install and configure Nginx
  hosts: webservers
  become: yes
  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: latest
        update_cache: yes
      when: ansible_os_family == 'Debian'

    - name: Install Nginx on CentOS
      yum:
        name: nginx
        state: latest
      when: ansible_os_family == 'RedHat'

    - name: Create web root directory
      file:
        path: /var/www/{{ domain }}
        state: directory
        mode: '0755'
        owner: www-data
        group: www-data

    - name: Copy index.html
      copy:
        content: "<html><body><h1>Welcome to {{ domain }}</h1></body></html>"
        dest: /var/www/{{ domain }}/index.html
        mode: '0644'

    - name: Configure Nginx virtual host
      template:
        src: nginx_vhost.j2
        dest: /etc/nginx/sites-available/{{ domain }}
      notify:
        - restart nginx

    - name: Enable site
      file:
        src: /etc/nginx/sites-available/{{ domain }}
        dest: /etc/nginx/sites-enabled/{{ domain }}
        state: link
      notify:
        - restart nginx

  handlers:
    - name: restart nginx
      service:
        name: nginx
        state: restarted

对应的Jinja2模板文件 nginx_vhost.j2:

server {
    listen 80;
    server_name {{ domain }} www.{{ domain }};

    root /var/www/{{ domain }};
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

4. 使用Docker自动化部署Nginx

#!/bin/bash

# Nginx Docker自动化部署脚本

# 创建本地目录存储配置和网站文件
mkdir -p ~/nginx/{conf,html,logs}

# 创建示例index.html
echo "<html><body><h1>Nginx in Docker</h1></body></html>" > ~/nginx/html/index.html

# 创建基本Nginx配置
cat > ~/nginx/conf/nginx.conf <<EOF
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                      '\$status \$body_bytes_sent "\$http_referer" '
                      '"\$http_user_agent" "\$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
    }
}
EOF

# 运行Nginx容器
docker run -d \
  --name my-nginx \
  -p 80:80 \
  -v ~/nginx/html:/usr/share/nginx/html \
  -v ~/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
  -v ~/nginx/logs:/var/log/nginx \
  nginx:latest

echo "Nginx容器已启动,访问 http://localhost 查看"

5. 高级功能:自动化SSL证书配置

#!/bin/bash

# Nginx SSL自动化配置脚本(使用Let's Encrypt)

# 检查是否已安装certbot
if ! command -v certbot &> /dev/null; then
    echo "安装certbot..."
    sudo apt-get install -y certbot python3-certbot-nginx
fi

# 参数检查
if [ "$#" -ne 1 ]; then
    echo "用法: $0 域名"
    exit 1
fi

DOMAIN=$1

# 获取SSL证书
sudo certbot --nginx -d $DOMAIN -d www.$DOMAIN

# 设置自动续期
(crontab -l 2>/dev/null; echo "0 12 * * * /usr/bin/certbot renew --quiet") | crontab -

echo "SSL证书已配置并设置自动续期"

注意事项

  1. 执行脚本前确保有足够的权限
  2. 根据您的Linux发行版调整包管理命令(apt/yum/dnf等)
  3. 生产环境建议添加更多的错误处理和日志记录
  4. 对于关键系统,建议先在测试环境验证脚本
  5. 定期备份Nginx配置

您可以根据实际需求组合或修改这些脚本片段。需要更具体的自动化功能可以进一步说明需求,我可以提供更有针对性的解决方案。