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
プチモンテ ※この記事を書いた人
![]() | |
![]() | 💻 ITスキル・経験 サーバー構築からWebアプリケーション開発。IoTをはじめとする電子工作、ロボット、人工知能やスマホ/OSアプリまで分野問わず経験。 画像処理/音声処理/アニメーション、3Dゲーム、会計ソフト、PDF作成/編集、逆アセンブラ、EXE/DLLファイルの書き換えなどのアプリを公開。詳しくは自己紹介へ |
| 🎵 音楽制作 BGMは楽器(音源)さえあれば、何でも制作可能。歌モノは主にロック、バラード、ポップスを制作。歌詞は抒情詩、抒情的な楽曲が多い。楽曲制作は🔰2023年12月中旬 ~ | |









