NGINX位置子句仅用于根域

如何在example.com上点击$request_filename ~ /sub1时只redirectsub1.example.com 。 例如,如果我在sub1.example.com ,击中/sub1不会redirect我也sub1.example.com ,而是实际的页面sub1.example.com/sub1

我的NGINXconfiguration:

 server { server_name .example.com; access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log; root /var/www/html/example; index index.php; location ~ \.php$ { if (-f $request_filename) { fastcgi_pass 127.0.0.1:9000; } fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location / { if ($request_filename ~ /sub1) { rewrite ^ http://sub1.example.com/? permanent; } if ($request_filename ~ /sub2) { rewrite ^ http://sub2.example.com/? permanent; } if (!-f $request_filename) { rewrite ^(.*)$ /index.php last; } } } 

我如何使用 location 子句只有根域?

更新@ Marcel:

 server { server_name .example.com; access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log; root /var/www/html/example; index index.php; location ~ \.php$ { if (-f $request_filename) { fastcgi_pass 127.0.0.1:9000; } fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location = /sub1 { if($host = "example.com") { rewrite ^ http://sub1.example.com permanent; } } location = /sub2 { if($host = "example.com") { rewrite ^ http://sub2.example.com permanent; } } location / { if (!-f $request_filename) { rewrite ^(.*)$ /index.php last; } } } 

不要使用If在里面的Location块。 最好在不同server_nameconfiguration中声明几个部分server {}

相反, if (-f $request_filename) {使用try_files指令。

Nginx以某种方式处理位置指令,具体取决于你拥有的指令。 这个链接指出了nginx的行为:

位置可以由前缀string定义,也可以由正则expression式定义。
正则expression式通过在前面添加“〜*”修饰符(用于不区分大小写的匹配)或用“〜”修饰符(用于区分大小写的匹配)来指定。

要查找与给定请求匹配的位置,nginx首先检查使用前缀string(前缀位置)定义的位置。 其中,最具体的一个被搜查。
然后按照它们在configuration文件中出现的顺序检查正则expression式。 正则expression式的search在第一次匹配时终止,并使用相应的configuration。

如果找不到正则expression式的匹配,则使用最具体的前缀位置的configuration。“

location /是通配符的位置,将匹配每个请求。

这是你的位置应该是:

 location ~ \.php$ { if (-f $request_filename) { fastcgi_pass 127.0.0.1:9000; } fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location = /sub1 { if($host = "example.com") { rewrite ^ http://sub1.example.com permanent; } } location = /sub2 { if($host = "example.com") { rewrite ^ http://sub2.example.com permanent; } } location / { if (!-f $request_filename) { rewrite ^(.*)$ /index.php last; } }