您的位置:

php artisan serve详解

php artisan serve是laravel框架自带的web服务器,其可以省略Apache和Nginx的设置,使得我们可以更加快速地构建我们的WEB项目。

一、简介

php artisan serve是laravel框架自带的web服务器,可以代替我们繁琐的Apache和Nginx设置操作,快速启动一个web服务,来运行我们的laravel应用程序。

在默认情况下,php artisan serve将会监听8000端口,只需在命令行中执行命令即可:

php artisan serve

课以访问 http://localhost:8000 来访问我们的应用程序。如果你需要更改端口号,可以使用--port参数:

php artisan serve --port=8080

这样我们就可以通过 http://localhost:8080 来访问我们的应用程序了。

二、支持HTTPS

默认情况下,php artisan serve不支持HTTPS,但我们可以通过传递--ssl选项并定义开发证书参数来启用SSL。

php artisan serve --ssl --port=443

在这个示例中,我们使用端口443来启用SSL。你可以通过自己的认证机构创建自己的开发证书,在这里我们使用自签发证书来进行示例说明。

首先,我们需要使用openssl创建证书私钥:

openssl genrsa -aes256 -out server.key 2048

接下来,我们可以生成自签名证书(public key):

openssl req -new -x509 -nodes -key server.key -sha256 -days 365 -out server.crt

在执行此命令时,我们将被请求提供必要的信息(例如国家/地区名称,组织名称等)以创建证书:

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:Hunan
Locality Name (eg, city) []:Changsha
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Your Company
Organizational Unit Name (eg, section) []:Your Division
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:xyz@example.com

完成后,我们在命令行中使用证书:

php artisan serve --ssl --port=443 --cert=/path/to/cert/server.crt --key=/path/to/cert/server.key

现在,你可以使用 https://localhost 来访问应用程序,浏览器会提示这是不安全的,但是作为开发环境,这是可以接受的。

三、自定义host和端口

如果你要监听特定的IP地址(不是localhost),可以使用--host选项:

php artisan serve --host=192.168.1.100

现在你可以使用 http://192.168.1.100 来访问你的应用程序。

同时,如果你的开发域名不是localhost,可以自定义hostname:

php artisan serve --host=example.com --port=8080

现在,你可以通过 http://example.com:8080 来访问你的应用程序。

四、设置自定义文档根目录

在laravel项目中,public目录是文档根目录,所有web请求会从这里开始。但是有时候,你可能需要设置自定义的文档根目录,比如需要访问一些额外的静态文件。

使用--docroot选项可以让php artisan serve使用自定义的文档根目录:

php artisan serve --docroot=/path/to/document/root

现在,文档根目录将切换到你自定义的路径。例如,如果你将--docroot设置为path/to/document/root,则位于path/to/document/root目录的index.php文件将会成为应用程序的主入口点。

总结:

php artisan serve是laravel框架自带的web服务器,有很多实用的参数来帮助我们快速开发我们的应用程序,这里主要介绍了如何更改端口,启用SSL,自定义host和端口,以及设置自定义文档根目录等功能。希望这篇文章对你有所帮助。