簡體   English   中英

如何在 Laravel 中以 root 身份創建公共文件夾?

[英]How to make public folder as root in Laravel?

我使用 Laravel 框架。 如您所知,它的目錄如下所示:

在此處輸入圖片說明

要打開我網站的主頁( Route::get('/', 'HomeController@index'); ),我需要打開目錄的/public文件夾。 換句話說,要查看我網站的第一頁,這里是 URL:

http://example.com/public

無論如何,只有我的域名( http://example.com/ )不是我的根。 如何以 root 身份創建/public文件夾?


目前我找到了一個解決方法。 我可以在根目錄上創建一個index.php並將重定向代碼寫入/public文件夾。 因此,當用戶輸入http://example.com/ ,它將自動重定向到http://example.com/public 但這仍然是丑陋的。 我不喜歡在 URL 中看到/public 有什么建議嗎?

有很多方法可以做到這一點。

您只需要從公共目錄中剪切index.php和 .htaccess 並將其粘貼到根目錄中即可,將index.php中的兩行替換為

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

最好的方法是.htaccess 在 Laravel 安裝的根目錄中創建.htaccess文件。 下面的代碼將適用於此。

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

您可以從這里閱讀: WAY TO DO

不要修改任何 Laravel 文件。 使用 Web 服務器(Apache 或 Nginx)將Laravel 項目指向public目錄

對於 Apache,您可以使用這些指令:

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

對於 nginx,您應該更改此行:

root /path_to_laravel_project/public;

第 1 步:將您的/public/index.php/public/htaccess文件作為/index.php/htaccess放入您的根目錄。
第 2 步:現在在 index.php 中進行更改

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

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

對於Ubuntu 20.04 ,對虛擬主機執行以下操作。 同樣在等待幾分鍾后,清除瀏覽器緩存並重新加載。

sudo mkdir /var/www/<your domain>/public
sudo chown -R $USER:$USER /var/www/<your domain>
sudo nano /etc/apache2/sites-available/<your domain>.conf

然后在文件中粘貼

<VirtualHost *:80>
    ServerName <your domain>
    ServerAlias www.<your domain>
    ServerAdmin <your email address>
    DocumentRoot /var/www/<your domain>/public
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

然后運行

sudo a2ensite <your domain>
sudo a2dissite 000-default
sudo systemctl reload apache2

nano /var/www/<your domain>/public/index.html

然后粘貼到文件中

<html>
  <head>
    <title><your domain></title>
  </head>
  <body>
    <center>
        <p>Site Under Maintenance</p>
    </center>
  </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM