在CentOS上配置Laravel路由,需要遵循以下步骤:
安装Laravel: 首先,确保你已经在CentOS上安装了PHP和Composer。然后,通过以下命令安装Laravel:
composer global require laravel/installer
确保将Composer的全局二进制文件目录添加到系统的PATH环境变量中。例如,如果你将Composer安装在/home/user/.composer/vendor/bin
,则需要将其添加到PATH中:
export PATH=$PATH:/home/user/.composer/vendor/bin
将上述命令添加到~/.bashrc
或~/.bash_profile
文件中,以便在每次打开新终端时自动设置PATH。
创建新的Laravel项目: 使用以下命令创建一个新的Laravel项目:
laravel new project_name
这将在当前目录下创建一个名为project_name
的新Laravel项目。
配置Web服务器: 在CentOS上,通常使用Apache或Nginx作为Web服务器。以下是配置这两种服务器的方法:
Apache:
启用mod_rewrite模块:
sudo yum install mod_rewrite
sudo systemctl enable httpd
sudo systemctl start httpd
sudo systemctl status httpd
在/etc/httpd/conf/httpd.conf
文件中启用AllowOverride:
sudo vi /etc/httpd/conf/httpd.conf
找到<Directory>
部分,将其更改为:
<Directory /var/www/html>
AllowOverride All
</Directory>
重启Apache服务:
sudo systemctl restart httpd
Nginx:
安装Nginx:
sudo yum install epel-release
sudo yum install nginx
启动Nginx服务:
sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx
在/etc/nginx/conf.d/default.conf
文件中配置Laravel项目:
server {
listen 80;
server_name example.com; # 替换为你的域名或公网IP
root /var/www/html/project_name/public; # 替换为你的Laravel项目路径
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
重启Nginx服务:
sudo systemctl restart nginx
配置Laravel路由:
在Laravel项目中,打开routes/web.php
文件,添加你需要的路由。例如:
Route::get('/', function () {
return 'Hello, World!';
});
Route::get('/about', function () {
return 'About page';
});
设置文件权限:
确保Laravel项目的storage
和bootstrap/cache
目录具有可写权限:
sudo chmod -R 775 /var/www/html/project_name/storage
sudo chmod -R 775 /var/www/html/project_name/bootstrap/cache
现在,你应该可以在浏览器中访问你的Laravel应用程序,并看到配置的路由。如果遇到问题,请检查Web服务器和Laravel项目的错误日志以获取更多信息。