Skip to content

Instantly share code, notes, and snippets.

@yidas
Last active January 12, 2022 07:10
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yidas/fc7228b6d7aad48d84461a254a77812f to your computer and use it in GitHub Desktop.
Save yidas/fc7228b6d7aad48d84461a254a77812f to your computer and use it in GitHub Desktop.
[Nginx] Nginx Configuration Guide & Samples (Subdirectory with PHP)

Nginx Configuration Guide & Samples

Subdirectory using Alias

root /var/www/html;

location /site2/ {
    
    alias /srv/www/project2/;
}

on request of /site2/top.gif, the file /srv/www/project2/top.gif will be sent.

Nginx Alias

Subdirectory with PHP

According to Nginx Alias above, you could define PHP location in that with SCRIPT_FILENAME setting for Subdirectory path.

location /site2/ {
    
    alias /srv/www/project2/;
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        # Apply the subdirectory base path to PHP script
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}

Pretty URI

If you need pretty URL such as Laravel PHP framework, you could seriously setup try_files with trick:

location /site2/ {
    
    alias /srv/www/project2/;
    
    # Pretty URI trick
    try_files $uri $uri/ /site2//site2/index.php?$query_string;
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        # Apply the subdirectory base path to PHP script
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment