ホーム > カテゴリ > PHP・Laravel・CakePHP >

Laravelをサブディレクトリで本稼働させる [Nginx/Apache]

1. Nginx

1-1. 前提

// プロジェクトのパス(ソース)
/home/ユーザー名/laravel/bbs

// やりたいこと
http://example.com/dev/bbs
でアクセス可能とする

1-2. xxx.conf

location /dev/bbs {
  alias /home/ユーザー名/laravel/bbs/public;
  try_files $uri $uri/ @laravel_1;

  index index.php index.html index.htm;
  location ~ \.php$ {
      fastcgi_pass   127.0.0.1:9000;
      fastcgi_index  index.php;
      include        fastcgi_params;
      fastcgi_param  SCRIPT_FILENAME /home/ユーザー名/laravel/bbs/public/index.php;
  }
}

location @laravel_1 {
    rewrite /dev/bbs/(.*)$ /dev/bbs/index.php?/$1 last;
}  

1-3. public\index.phpに追記

このままだと http://example.com/dev/bbs/public/index.php でアクセス可能なので、public\index.php の先頭に次のコードを追記します。

$url = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
if ($url == 'http://example.com/dev/bbs/public/index.php'){
  header('Location: http://example.com/dev/bbs');
  exit;
}

1-4. Nginxの再起動

sudo systemctl restart nginx

2. Apache

WSL(Ubuntu16.04)のApacheで確認。他の環境でも同様だと思われます。

2-1. 前提

// プロジェクトのパス(ソース)
// ※D:\laravel\bbsの事です。
/mnt/d/laravel/bbs

// やりたいこと
http://localhost/test/
でアクセス可能とする

2-2. rewrite_moduleの有効確認

// モジュールの状態を確認
apache2ctl -M  

rewrite_moduleが含まれていない場合は次のコマンドで有効にする。

// mod_rewriteの有効化
sudo a2enmod rewrite

// mod_rewriteの無効化
//sudo a2dismod rewrite

※WSLだとrewrite_moduleはデフォルトはオフになっているようです。

2-3. 000-default.confの編集

000-default.confは書き込み権限がないので、rootでログインする。

// ルートログイン
su root

// 000-default.confの編集
vi /etc/apache2/sites-available/000-default.conf

末尾に以下を追記する。

Alias /test /mnt/d/laravel/bbs/public
<Directory "/mnt/d/laravel/bbs/public">
  Options Includes ExecCGI FollowSymLinks
  AllowOverride All
  Require all granted
  Order allow,deny
  Allow from all
</Directory>

2-4. \public\.htaccessの編集

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    
    # RewriteRule ^ %1 [L,R=301] ココはコメントにする

    # 以下は追記部分 ----------------------
    RewriteRule ^(.*)/$ /test/$1 [L,R=301]
    RewriteBase  /test/
    # ココまで ---------------------------- 
 
    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

2-5. Apacheの再起動

sudo service apache2 restart

2-6. Apacheの参考文献

ApacheのAliasと.htaccessでLaravelをサブディレクトリで動かす
Ubuntu server 18.04: Apache2 のインストールと設定,運用





関連記事



公開日:2020年11月15日
記事NO:02846