当前位置:首页 > nginx > 正文

nginx 如何配置跳转(修改nginx 指定配置路径)

  • nginx
  • 2024-04-06 19:12:47
  • 5361
Nginx 重定向配置
Nginx 是一款流行的 Web 服务器,可以通过重定向功能将访问者从一个 URL 重定向到另一个 URL。 这在以下情况下非常有用:
当网页被移动或重命名时
当需要根据特定条件进行重定向时
当需要保护特定资源时
配置重定向
在 Nginx 配置文件中,可以在 server 块中使用 rewrite 指令配置重定向。 语法如下:
rewrite [regex] [replacement] [flags];
其中:
regex 是要匹配的正则表达式
replacement 是要重定向到的目标 URL
flags 是可选的修饰符,例如 permanent(发出 301 永久重定向)或 temporary(发出 302 临时重定向)
示例
将所有请求重定向到 http://example.com
server {
listen 80;
rewrite ^(.)$ http://example.com$1 permanent;
}
将特定目录下的所有请求重定向到另一个目录
server {
location /old_dir {
rewrite ^/old_dir/(.) /new_dir/$1 permanent;
}
}
根据请求中的参数重定向
server {
location / {
rewrite ^/(.+)/(.)$ $1.php?$2 permanent;
}
}
验证重定向
完成配置后,可以使用以下命令验证重定向是否工作正常:
curl -IL http://your_domain.com/old_url
输出应类似于以下内容:
HTTP/1.1 301 Moved Permanently
Location: http://example.com/new_url
这表示所有请求都将从 /old_url 永久重定向到 /new_url。