Search code examples
web-servicesnginxfastcgi

nginx try_files with $host


In my configuration i use the host-name($host) as directory so i don't need to make a entry for each domain in the config (only for development purpose)

one issue is that try_files failed i tried different ways but all of them without success.

  • try_files html\$host$uri =404;
  • try_files $document_root\$host$uri =404;
  • try_files $uri =404;
  • try_files $document_root\$host$fastcgi_script_name =404;

    server {
    listen       80;
    server_name  default;
    
    charset UTF-8;
    
    #access_log  logs/host.access.log  main;
    
    # redirect server error pages to the static pages
    error_page  500 502 503 504  /error/50x.html;
    error_page  404 = /error/404.html;
    error_page  403 = /error/403.html;
    location ^~ /error/ {
        internal;
        root   html/default;
    }
    
    location / {
        root   html/$host;
        index  index.php index.html index.htm;
    }
    
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
        #try_files html\$host$uri =404;
        #try_files $document_root\$host$uri =404;
        #try_files $uri =404;
        #try_files $document_root\$host$fastcgi_script_name =404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root\$host$fastcgi_script_name;
        include        fastcgi_params;
    }
    

Solution

  • The concept it self is correct, but you are applying it in the wrong place, you should place this as a root for the server, not in the try_files

    Also I believe you should use $http_host not $host, refer to this answer to know the difference

    I don't know why your paths are not absolute, they should start with /

    I'll add changes to your current posted config

    server {
        #since you will match multiple domains I removed the server_name
        listen 80 default_server; 
        charset UTF-8; # don't really need this but it won't hurt.
        root   /usr/share/nginx/html/$http_host; #assuming this path
        index  index.php index.html index.htm;
        # redirect server error pages to the static pages
        error_page  500 502 503 504  /error/50x.html;
        error_page  404 = /error/404.html;
        error_page  403 = /error/403.html;
    
        location ^~ /error/ {
            internal;
            root   /usr/share/nginx/html/default;
        }
    
        location / {
            try_files $uri $uri/ /index.php$is_args$query_string;
        }
    
        location ~ \.php$ {
        # these are the minimal required parameters.
        include        fastcgi_params;
        fastcgi_pass   127.0.0.1:9000;
        }
    }