# 移除 public 結尾

Laravel 框架中，唯一對外公開的目錄只有 public，這也是為什麼我們連入網站時，網址的最後面都要加 public，可是這樣實在不太好看，這節就要說明如何將它從網址中移除。

## 網址、主網域、網站目錄

假設最後想要使用的網址型式，有 3 種，對應到後面說明的 3 種方法：

* [www.myweb.com](http://www.myweb.com)    (方法1或2)
* [www.myweb.com/blog/](http://www.myweb.com/blog/) (方法3)
* blog.myweb.com (方法2)

那主網域就會是：

```
myweb.com
```

假設網站目錄為 blog，並且放在 www 目錄下，完整路徑為 /var/www/blog。

## 設定

### 方法1 － 單一網站

如果你的網站伺服器只打算有一個網站，而且不打算使用虛擬網站。

編輯 Apache 的設定檔 httpd.conf，將 DocumentRoot 指定到 /var/www/blog/public，例如：

```
DocumentRoot /var/www/blog/public
```

這樣表示網站的根目錄直接指向 public。接著只要設定 DNS 的 A 主機為 www 即可。

### 方法2 - 虛擬網站

如果網站伺服器中有多個網站，可以使用虛擬網站來設定，編輯 Apache 的設定檔 httpd.conf (新版本的設定檔可能將 VirtualHost 的部份移到另一個獨立檔案)，找到 \ (通常在檔案的最尾端)，將它的 DocumentRoot 指定到 /var/www/blog/public，例如：

&#x20;DocumentRoot /var/www/blog/public ServerName [www.myweb.com](http://www.myweb.com)

這樣表示你要使用 [www.myweb.com](http://www.myweb.com) 當網址，DNS 指定 A 主機為 www。

如果要使用 blog.myweb.com 當網址，則把 ServerName 改成 blog.myweb.com，同時 DNS 新增一個 CNAME 名稱為 blog。

### 方法3 － 移動 public 目錄

這裡假定你的 DNS 已經有 A 主機，名稱是 www。

前面兩種方法都是透過設定伺服器的設定檔，將網站的 DocumentRoot 指定到 public。方法 3 則是直接移動 Laravel 網站的 public 目錄，將它放到網站根目錄，但是必須調整 Laravel 中的路徑設定。

#### 1.移動 public 到網站根目錄

將 blog 下的 public 移動到網站根目錄，等於和 blog 同一目錄，像這樣：

```
www/blog
www/public
```

#### 2.目錄重新命名

將原本的 blog 改為其他名稱，例如：blog-web，名稱自訂，使用者看不到這個目錄。接著 public 改為 blog，這個就是要讓使用者開啟的網站目錄。

結果：

```
www/blog -> www/blog-web
www/public -> www/blog
```

#### 3.修改設定

修改原本的 public (現改名為 blog) 目錄下的 index.php

原本

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

改為

```
require __DIR__.'/../blog-web/bootstrap/autoload.php';
$app = require_once __DIR__.'/../blog-web/bootstrap/start.php';
```

說明：

這裡要調整路徑，因為 public 目錄被往上提了一層，和原目錄成為同一層，所以必須在原本的路徑中加入 /blog-web 。\_*DIR\_* 是指 public 目錄本身。

接著修改 blog-web 目錄下的 bootstrap/paths.php

原本

```
'public' => __DIR__.'/../public',
```

改為

```
'public' => __DIR__.'/../../blog',
```

也是路徑的調整。.. 是指父層目錄。

現在這個 blog 目錄就是這個網站的進入點，它會連結到 blog-web 去執行整個網站的程式。網址會是：

```
www.myweb.com/blog
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tony915.gitbook.io/laravel-4-2/fu-lu/remove_public_tail.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
