想要达到的效果
需要一个按url中的日期(格式为yyyymmdd)判断跳转,当日期为当前日期时到172.16.0.17:1789,非当前日期proxy_pass跳转到172.16.0.17:3789的nginx路由配置文件。示例url如下:
/hw-storage/jxc/img/20230324/100/jxcvim11111.png
/hw-storage/sss/img/20230325/100/jxcvm12v311.png
/hw-storage/x23/img/20230607/100/jxc543vv111.png
路由配置示例
Nginx路由配置示例
server {
listen 80;
server_name example.com;
location / {
# 重定向到 https://example.com 进行安全传输
return 301 https://example.com$request_uri;
}
}
server {
listen 443 ssl;
server_name example.com;
# SSL 证书和私钥文件配置
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location ~* ^/hw-storage/.*/img/(\d{
8})/.* {
# 获取 URL 中的日期参数
set $date $1;
# 获取当前日期(以服务器本地时间为准)
set $current_date $time_iso8601;
set $current_date_formatted $current_date;
# 格式化当前日期为 yyyymmdd 格式
if ($current_date ~* "^(.+)-(.+)-(.+)T") {
set $current_date_formatted $1$2$3;
}
if ($date = $current_date_formatted) {
# 当日期为当前日期时跳到 172.16.0.17:1789
proxy_pass http://172.16.0.17:1789;
} else {
# 当日期不为当前日期时跳到 172.16.0.17:3789
proxy_pass http://172.16.0.17:3789;
}
# 额外的安全性防范
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header X-Frame-Options "SAMEORIGIN";
add_header Content-Security-Policy "default-src 'self';";
}
}
例子中使用了正则表达式来匹配URL中的日期,设置了 $date
变量用于获取日期参数。然后使用 $time_iso8601
变量获取当前日期,再格式化成 yyyymmdd
格式的 $current_date_formatted
变量。根据比较日期和当前日期的结果,使用相应的 proxy_pass
语句进行跳转。最后还加入了一些安全性防范的 HTTP 头信息。