问题描述:
博客地址: http://blog.mufeng.tech:7078/home
想要隐藏 7078 端口号,通过 http://blog.mufeng.tech/home 就可正常访问
实现方法
要在 Nginx 中隐藏端口并通过默认的 HTTP 或 HTTPS 端口访问你的 Vue 博客,可以按照以下步骤操作:
- 修改 Nginx 配置文件
确保你在 Nginx 配置中将 7078 端口的服务代理到默认的 80(HTTP)或 443(HTTPS)端口。
示例配置:
server {
listen 80;
server_name blog.mufeng.tech;
location / {
proxy_pass http://127.0.0.1:7078; # 将请求转发到 7078 端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 静态文件缓存(可选)
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|otf|eot|ttc|map)$ {
expires max;
log_not_found off;
}
}
- 检查 DNS 配置
确保域名 blog.mufeng.tech 的 DNS 记录已经指向你服务器的公网 IP 地址。
• A记录: blog.mufeng.tech -> <你的服务器IP>
• 如果使用 HTTPS,还需要确保 SSL 证书正确配置。
- 检查 Vue 路由配置
如果你的 Vue 项目使用 history 模式路由,需要为 Nginx 添加一个默认的 index.html 路径处理,避免刷新页面时返回 404。
在 Nginx 配置中添加以下内容:
location / {
try_files $uri /index.html;
}
完整配置如下:
server {
listen 80;
server_name blog.mufeng.tech;
location / {
root /path/to/your/vue/dist; # Vue 项目打包后的文件目录
index index.html;
try_files $uri /index.html; # 避免 history 模式刷新 404
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|otf|eot|ttc|map)$ {
expires max;
log_not_found off;
}
}
- 配置 HTTPS(可选)
如果需要 HTTPS 支持,可以使用免费的 Let’s Encrypt SSL 证书,通过工具 certbot 自动生成并配置。
HTTPS 配置示例:
server {
listen 443 ssl;
server_name blog.mufeng.tech;
ssl_certificate /etc/letsencrypt/live/blog.mufeng.tech/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/blog.mufeng.tech/privkey.pem;
location / {
proxy_pass http://127.0.0.1:7078;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
try_files $uri /index.html;
}
}
同时,还需要在 80 端口上添加 HTTP 转 HTTPS 的跳转:
server {
listen 80;
server_name blog.mufeng.tech;
return 301 https://$host$request_uri;
}
- 重启 Nginx 服务
修改完成后,重启 Nginx 使配置生效:
sudo nginx -t # 检查配置是否正确
sudo systemctl restart nginx
验证效果
• 打开浏览器访问 http://blog.mufeng.tech/home(如果启用了 HTTPS,则为 https://blog.mufeng.tech/home)。
• 确认端口隐藏且页面正常加载。
网友评论