NGINX location clause for only root domain
How do I only redirect too sub1.example.com
when hitting $request_filename ~ /sub1
on example.com
. For example if I'm on sub1.example.com
, hitting /sub1
wont redirect me back too sub1.example.com
but rather the actual page sub1.example.com/sub1
?
My NGINX config:
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;
}
}
}
How do I use the location
clause for only root domain?
Update @ 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;
}
}
}
Don't use If
inside Location
block. much better to declare several sections server {}
in config with different server_name
.
Instead if (-f $request_filename) {
use try_files
directive.