Skip to content

Instantly share code, notes, and snippets.

Last active August 6, 2021 14:50
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Yii2 Server Configuration for Nginx & Apache (Subdirectory)

Yii2 Server Configuration for Nginx & Apache (Subdirectory)

It's easy to configurate a Yii2 server site with directory protection:

Yii2 Web Server Configuration

Sub Directory Site Application

With using Sub Directory for Yii2, you could set sub-directory path into yii2's config:

$config = [
    'components' => [
        'request' => [
            'cookieValidationKey' => '',
            'baseUrl' => '/subyii'

After that, it would be correct to bind URL when you use Url generator:

// echo `/subyii` 
echo \yii\helpers\Url::to(['/']);

Nginx Configuration

Basic Subdirectory

With same path included /public, for example: /sublara/

# Subdirectory Laravel Application Configuration
# App directories protection
location /subyii/ {                                                 
    return 403;                                                                           
# Yii2 public
location /subyii/web/ {                                          
    try_files $uri $uri/ /subyii/web/index.php?$is_args$args;

After above setting:

  • Access Yii2 web: //hostname/subyii/web/
  • Protect Yii2 app directories: //hostname/subyii/ (/sublara/composer.json)

Protected Subdirectory

Using alias to implement different subdiretory pointed to specified project path:

location /site2/ {
    alias /srv/www/yii2-app2/web/;
    # Pretty URI trick (Variable are same as location path)
    try_files $uri $uri/ /site2//site2/index.php?$is_args$args;
    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;

try_files with trick


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