HTTP重定向是Web服务中常见的流量引导机制,用于实现域名跳转、HTTPS强制升级或URL结构优化。Linux环境下主流Web服务器(Nginx/Apache)均提供灵活的重定向配置方案。
一、Nginx重定向配置
基础跳转配置
在server块中添加return指令实现即时重定向:
nginx复制代码
| server { | |
|---|---|
| listen 80; | |
| server_name old.example.com; | |
| return 301 new.example.com$request_uri; # 301永久重定向 | |
| } |
正则匹配复杂规则
使用rewrite指令处理动态路径:
nginx复制代码
| location /old-path/ { | |
|---|---|
| rewrite ^/old-path/(.*)1 permanent; # 永久重定向保留路径参数 | |
| } |
HTTPS强制跳转
结合$scheme变量实现协议升级:
nginx复制代码
| server { | |
|---|---|
| listen 80; | |
| server_name example.com; | |
| return 301 https://request_uri; # 全站HTTPS跳转 | |
| } |
二、Apache重定向配置
简单域名跳转
在虚拟主机配置中使用Redirect指令:
apache复制代码
| <VirtualHost *:80> | |
|---|---|
| ServerName old.example.com | |
| Redirect 301 / new.example.com/ | |
路径重写规则
启用mod_rewrite模块实现复杂逻辑:
apache复制代码
| RewriteEngine On | |
|---|---|
| RewriteRule ^/old-path/(.*)1 [R=301,L] # 路径重写+永久重定向 |
HTTPS强制配置
结合mod_ssl模块实现协议升级:
apache复制代码
| <VirtualHost *:80> | |
|---|---|
| ServerName example.com | |
| RewriteEngine On | |
| RewriteCond %{HTTPS} off | |
| RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] | |
通过合理配置重定向规则,可实现SEO优化、安全加固及站点架构平滑迁移。生产环境修改前建议在测试环境验证,并使用nginx -t或apachectl configtest检查配置语法。