1
0
md/Nginx配置域名反代内网穿透服务.md

81 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 一键运行脚本
```
sudo bash -d 域名 -p 内网穿透的端口号
```
### 脚本内容
```
#!/bin/bash
# 解析命令行参数
while getopts d:p: flag
do
case "${flag}" in
d) DOMAIN=${OPTARG};;
p) SERVER_PORT=${OPTARG};;
?)
echo "错误:未知参数。"
echo "用法:$0 -d example.com -p 8080"
exit 1;;
esac
done
# 检查 DOMAIN 是否已提供
if [ -z "$DOMAIN" ]; then
echo "错误:必须使用 -d 参数指定域名。"
echo "用法:$0 -d example.com -p 8080"
exit 1
fi
# 检查 SERVER_PORT 是否已提供
if [ -z "$SERVER_PORT" ]; then
echo "错误:必须使用 -p 参数指定端口号。"
echo "用法sudo bash -d example.com -p 8080"
exit 1
fi
FILE="/etc/nginx/sites-available/$DOMAIN"
LINK="/etc/nginx/sites-enabled/$DOMAIN"
# 创建站点配置文件
sudo tee "$FILE" > /dev/null <<EOF
server {
listen 80;
server_name $DOMAIN;
location / {
proxy_pass http://127.0.0.1:$SERVER_PORT;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_buffering on;
proxy_buffer_size 128k;
proxy_buffers 8 256k;
proxy_busy_buffers_size 256k;
proxy_max_temp_file_size 100m;
}
# 日志配置
access_log /var/log/nginx/${DOMAIN}.access.log;
error_log /var/log/nginx/${DOMAIN}.error.log;
}
EOF
# 创建软链接并重启 Nginx
sudo ln -sf "$FILE" "$LINK"
sudo systemctl reload nginx
echo "Nginx 配置已为域名 $DOMAIN 创建,代理到端口 $SERVER_PORT并已重载服务。"
```