在Linux上使用Laravel搭建网站是一个相对直接的过程,以下是详细的步骤:
首先,确保你的Linux系统已经安装了以下软件:
你可以使用包管理器来安装PHP。例如,在Ubuntu上:
sudo apt update
sudo apt install php php-cli php-fpm php-mysql php-zip php-gd php-mbstring php-curl php-xml php-pear php-bcmath
从Composer官网下载并安装Composer:
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo apt update
sudo apt install nginx
sudo apt update
sudo apt install apache2
sudo apt update
sudo apt install mysql-server
编辑Nginx配置文件(通常位于/etc/nginx/sites-available/default),添加一个服务器块:
server {
listen 80;
server_name yourdomain.com;
root /var/www/yourproject;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
然后启用配置:
sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
编辑Apache配置文件(通常位于/etc/apache2/sites-available/000-default.conf),添加一个虚拟主机:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/yourproject
<Directory /var/www/yourproject>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
然后启用配置:
sudo a2enmod rewrite
sudo systemctl restart apache2
使用Composer创建一个新的Laravel项目:
cd /var/www
sudo composer create-project --prefer-dist laravel/laravel yourproject
编辑.env文件,配置数据库连接:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=yourdatabase
DB_USERNAME=yourusername
DB_PASSWORD=yourpassword
然后运行迁移命令创建数据库表:
cd yourproject
php artisan migrate
确保Laravel项目的storage和bootstrap/cache目录可写:
sudo chown -R www-data:www-data /var/www/yourproject
sudo chmod -R 755 /var/www/yourproject
sudo chmod -R 777 /var/www/yourproject/storage
sudo chmod -R 777 /var/www/yourproject/bootstrap/cache
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl start apache2
sudo systemctl enable apache2
打开浏览器,访问你的域名(例如http://yourdomain.com),你应该能看到Laravel的欢迎页面。
为了安全起见,建议为你的网站配置SSL证书。你可以使用Let’s Encrypt免费获取SSL证书:
sudo apt install certbot python3-certbot-nginx # 对于Nginx
sudo certbot --nginx -d yourdomain.com
对于Apache:
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d yourdomain.com
完成以上步骤后,你的Laravel网站应该已经成功搭建并运行在Linux服务器上了。