在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項目的錯誤日志以獲取更多信息。