Laravel Project で /public のパスを削除する方法

November 12, 2019

はじめに

Laravel Project で作成したアプリケーションにアクセスする際に project_dir/public ではなく project_dir/ でアクセスしたいですよね。
例えば DocumentRoot が /var/www/html だったときに、/var/www/html/project_dir/ 配下に作成したアプリケーションにアクセスする際に http://example.com/project\_dir/public/ ではなく http://example.com/project\_dir/ でアプリケーションを利用可能としたい、という意図です。
本エントリでは .htaccess を用いてそれを実現する方法について記載します。

プロジェクトの作成

まずは適当にプロジェクトを作成します。

$ laravel new sample_project  
Crafting application...  
  
...  
  
Application ready! Build something amazing.  
  
$ cd sample_project  
$ chmod -R 777 storage/  
$ chmod -R 777 bootstrap/cache/  

あとは適当に Controller 作って Blade 作って Route 書くだけです。

$ php artisan make:controller HelloController  
Controller created successfully.  
app/Http/Controllers/HelloController.php
<?php  
  
namespace App\Http\Controllers;  
  
use Illuminate\Http\Request;  
  
class HelloController extends Controller  
{  
    public function __invoke() {  
        return view('index');   
    }  
}  
resources/views/index.blade.php
<html>  
  <head>  
    <title>Sample Project</title>  
  </head>  
  <body>  
    <h2>This is a sample project</h2>
  </body>  
</html>  
routes/web.php
<?php  
  
Route::get('/', 'HelloController');  

で、まずは http://example.com/sample_project/public/ の形でアクセスしてみましょう。

f:id:shiro_kochi:2018××××××××:plain:w100:left

ひとまずプロジェクトは完成です。

.htaccess を使う

ここで、http://example.com/sample_project/ の形でアクセスできるように、以下の .htaccess を sample_project/ 配下に配置します。

.htaccess
<IfModule mod_rewrite.c>  
    <IfModule mod_negotiation.c>  
        Options -MultiViews  
    </IfModule>  
      
    RewriteEngine On  
      
    RewriteCond %{REQUEST_FILENAME} -d [OR]  
    RewriteCond %{REQUEST_FILENAME} -f  
    RewriteRule ^ ^$1 [N]  
  
    RewriteCond %{REQUEST_URI} (\.\w+$) [NC]  
    RewriteRule ^(.*)$ public/$1   
  
    RewriteCond %{REQUEST_FILENAME} !-d  
    RewriteCond %{REQUEST_FILENAME} !-f  
    RewriteRule ^ server.php  
  
</IfModule>  

これだけです。
早速 http://example.com/sample_project/ でアクセスしてみましょう。

f:id:shiro_kochi:2018××××××××:plain:w100:left

簡単ですね!


 © 2023, Dealing with Ambiguity