大网数据广告活动
服务器运维问答

NGINX redirect if user agent contains XYZ

· 52CE 我爱测

I have redirected my site from http to https. I want to allow the useragent XYZ and XYZ whatever to enter both http and https versions. Now the vhost looks like this: server { listen 80; server_name example.com www.example.com; r…

问题原文

原帖链接 · Pikk · CC BY-SA 3.0

I have redirected my site from http to https. I want to allow the useragent XYZ and XYZ whatever to enter both http and https versions.

Now the vhost looks like this:

server {
        listen 80;
        server_name example.com www.example.com;
        rewrite  ^/(.*)$  https://www.example.com/$1 permanent;
}

How can I edit it, in order to allow agents that contain XYZ to see both HTTP and HTTPS? In order words... how to disable the redirect for such agents?

I tried

if ($http_user_agent ~* "^XYZ$") {
   rewrite ^/(.*)$ https://www.example.com/$1 permanent;
}

But this seems to redirect only XYZ. But I need to disable the redirect if XYZ, not strict XYZ, but containing XYZ...

已采纳解答

原帖链接 · JayMcTee · CC BY-SA 3.0

With ~* you are attempting to loosely match the string, but your regex is ^XYZ$ which says match only if it starts with XYZ and only if it ends in XYZ. That's not loose at all. You are kind of contradicting yourself there.

See documentation here: http://nginx.org/en/docs/http/ngx_http_core_module.html#location

You probably want to adjust your regex to allow for more variations. From your question it's hard for us to know what you would like to match though. Possibly something like:

if ($http_user_agent ~* ".*XYZ.*") {
   rewrite ^/(.*)$ https://www.example.com/$1 permanent;
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-07-25)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。