How to make public folder as root in Laravel?

2020-08-25 02:18发布

问题:

I use Laravel framework. As you know, its directory looks like this:

To open the homepage of my website (Route::get('/', 'HomeController@index');) I need to open /public folder of directory. In other word, to see the first page of my website, here is the URL:

http://example.com/public

anyway, only my domainname (http://example.com/) isn't my root. How can I make /public folder as root?


Curently I've found a workaround. I can create an index.php on the root and write a redirect code to /public folder. So when user enters http://example.com/, it will be redirected to http://example.com/public automatically. But still that's ugly. I don't like to see /public in the URL. Any suggestion?

回答1:

There are many ways to do this.

You just need to cut index.php and .htaccess from public directory and paste it in the root directory, that's all and replace two lines in index.php as

require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';

Best way to do is .htaccess. Create .htaccess file in root directory in Laravel installation. And the below code will work for this.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

You can read from here: WAY TO DO



回答2:

Do not mofidy any Laravel files. Use web server (Apache or Nginx) to point Laravel project to public directory.

For Apache you can use these directives:

DocumentRoot "/path_to_laravel_project/public"
<Directory "/path_to_laravel_project/public">

For nginx, you should change this line:

root /path_to_laravel_project/public;


回答3:

Step 1: Put your /public/index.php and /public/htaccess file to your root directory as /index.php and /htaccess .
Step 2: Now Make changes in your index.php

require __DIR__.'/../bootstrap/autoload.php'; //OLD code
$app = require_once __DIR__.'/../bootstrap/app.php';

to

 require __DIR__.'./bootstrap/autoload.php'; //NEW code
 $app = require_once __DIR__.'./bootstrap/app.php';


标签: php laravel