在您自己的伺服器上設定 Laravel:DIY 指南
Originally published on bcd.dev
Before you go through the pain and challenge of configuring your own server you should perhaps consider Laravel forge. I trust they would know better how to deploy a laravel app.
For curious minded people, this is part of a bigger series Do it yourself series
Components
- webserver
- nginx
- database
- mysql
- php
- composer
- node
- npm / yarn
- scheduler
- firewall
- log
- papertrail
- search
- elastic search
- algolia
- other third party services
- redis
Basic build
recepee on an ubuntu server (22-10)
- mysql
- php
- composer
- node
- nginx
- queue
Requirements
- VPS Server
- Valid DNS record pointing to your server
Mysql
sudo apt-get install -y mysql-server # Init project by creating a user with a dedicated database name=$1 username=${2:-$name} password=${3:-$name} root_username=${4:-'root'} root_password=${5:-''} echo '' > tmp.sql echo "CREATE USER $name@localhost identified by \"$password\";" >> tmp.sql echo "CREATE DATABASE $name charset utf8 collate utf8_general_ci;" >> tmp.sql echo "GRANT ALL PRIVILEGES ON $name.* to $name@localhost;" >> tmp.sql mysql -u$root_username -p$root_password -e "source tmp.sql" mysql -u$root_username -p$root_password -e "CREATE DATABASE $name charset utf8 collate utf8_general_ci;"
Php
sudo apt install -y software-properties-common sudo add-apt-repository ppa:ondrej/php sudo apt update # php with some extensions PHP_VERSION=${1:-'8.2'} sudo apt-get install -y "php$PHP_VERSION" php$PHP_VERSION-{common,cli,fpm,zip,xml,pdo,mysql,mbstring,tokenizer,ctype,curl,common,curl,gd,intl,sqlite3,xmlrpc,xsl,soap,opcache,readline,xdebug,bcmath}
Composer
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" # For simplicity purpose, we are skipping the hash check. That is a crucial step you wouldn't want to skip when downloading stuff on the internet # Hash below matches composer version 2.1.3 # php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');" sudo mv composer.phar /usr/local/bin/composer
Node
You can get node on their website but I prefer getting specific version from node version manager (nvm)
version=${1:-'20'} echo "Installing nvm + node $version" wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash source ~/.bashrc nvm install $version # Optional but I like yarn so here we go nvm exec $version npm i yarn -g
Nginx
# Making sure apache is not installed to avoid conflict on port 80 sudo apt-get remove -y apache sudo apt-get install -y nginx rm /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default name=$1 # site.domain webroot=${3:-"/var/www/vhosts/$name"} mkdir -p $webroot touch "/etc/nginx/sites-available/$name.conf" ln -s "/etc/nginx/sites-available/$name.conf" "/etc/nginx/sites-enabled/$name.conf" cat >> "/etc/nginx/sites-available/$name.conf" << EOF server { listen 80 default_server; listen [::]:80 default_server; root $webroot; server_name $name www.$name; } EOF
Secure traffic using HTTPS
At this point we are running a web server on port 80. However everyone can see the content flowing through the networking. Welcome https.
domain=$1 email=${2:-"your@email.com"} sudo apt-get install -y python3-certbot-nginx # manual # certbot certonly -a manual --rsa-key-size 4096 --email $email -d $domain -d www.$domain # auto ## With base nginx config certbot certonly --nginx --rsa-key-size 4096 --email $email -d $domain -d www.$domain
When the steps above succeed you can carry on with nginx config for ssl. The following will redirect all non secure connection (80) to secure connection (443)
# Usage ./laravel.sh site.domain 8.2 ~/sites ## Dependencies: letsencrypt, php$php_version, php$php_version-fpm # sudo apt-get install -y php$php_version php$php_version-fpm name=$1 # site.domain user=$2 php_version=${3:-'8.2'} root=${4:-"/var/www/vhosts/$name"} webroot=${5:-"/var/www/vhosts/$name/public"} touch /etc/nginx/sites-available/$name.conf ln -s /etc/nginx/sites-available/$name.conf /etc/nginx/sites-enabled/$name.conf mkdir -p /var/www/vhosts/$name/storage/logs touch /var/www/vhosts/$name/storage/logs/error.log touch /var/www/vhosts/$name/storage/logs/access.log cat >> /etc/nginx/sites-available/$name.conf << EOF # Force HTTPS server { listen 80; listen [::]:80; server_name $name www.$name; return 301 https://$name\$request_uri; } # Force www less version' server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name www.$name; ssl_certificate /etc/letsencrypt/live/$name/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/$name/privkey.pem; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; return 301 https://$name\$request_uri; } server { server_name $name; # SSL config listen 443 ssl http2; listen [::]:443 ssl http2; server_tokens off; ssl_buffer_size 8k; ssl_protocols TLSv1.3 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5; ssl_ecdh_curve secp384r1; ssl_session_tickets off; # OCSP stapling ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4; ssl_certificate /etc/letsencrypt/live/$name/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/$name/privkey.pem; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # End of SSL config add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; add_header X-XSS-Protection "1; mode=block"; charset utf-8; index index.php index.html; error_log $root/storage/logs/error.log; access_log $root/storage/logs/access.log; root $webroot; error_page 404 /index.php; add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } location / { try_files \$uri \$uri/ /index.php?\$query_string; gzip_static on; proxy_set_header Host \$server_name; proxy_set_header X-Real-IP \$remote_addr; proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto \$scheme; } location ~ \.php$ { try_files \$uri /index.php =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/run/php/php$php_version-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name; fastcgi_param PATH_INFO \$fastcgi_path_info; fastcgi_buffers 8 64k; fastcgi_buffer_size 128k; fastcgi_connect_timeout 3000; fastcgi_send_timeout 3000; fastcgi_read_timeout 3000; } location ~ /\.(?!well-known).* { deny all; } # Define caching rules for static images location ~* \.(jpg|jpeg|png|gif|ico)$ { expires 30d; # adjust the caching duration as needed add_header Cache-Control "public, max-age=2592000"; } gzip on; gzip_types text/plain text/css application/javascript image/*; client_max_body_size 128m; # For unlimited # client_max_body_size 0; } EOF # permissions sudo find storage -type f -exec chmod 664 {} \; sudo find storage -type d -exec chmod 775 {} \; sudo chmod -R ug+rwx storage bootstrap/cache sudo chgrp -R www-data storage bootstrap/cache sudo usermod -aG $user www-data sudo chown $user:www-data -R storage bootstrap/cache # Check file exists # /etc/ssl/dhparams.pem # Generate if not # openssl dhparam -out /etc/ssl/dhparams.pem 4096 cat >> /etc/php/$php_version/cli/php.ini << EOF post_max_size=128M upload_max_filesize=128M max_upload_file=50 EOF
Auto renew certificate
# DISCLAIMER: it is safer to edit cron file using crontab dedicated command # That being see given this is a script we likely want to have automated /var/spool/cron/crontabs ## cron job to auto renew every 3 months for you crontab -e # 0 0 1 */3 * /usr/bin/certbot renew --quiet ## I saw people doing it monthly # 0 0 1 * *
Queue
#! /bin/bash user=${0:-$(USER)} root_dir="/home/$user/www/" processes=4 sudo apt get install -y supervisor cat >> /etc/supervisor/conf.d/laravel-worker.conf << EOF process_name=%(program_name)s_%(process_num)02d command=php ${root_dir}/artisan queue:work --sleep=3 --tries=3 --max-time=3600 autostart=true autorestart=true stopasgroup=true killasgroup=true user=${user} numprocs=${processes} redirect_stderr=true stdout_logfile=${root_dir}/storage/logs/worker.log stopwaitsecs=3600 EOF sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl start all
Conclusion
No conclusion as this is a starting point only but gets you an operational laravel app.
Made a lot of arbitrary choices. Adapt for your usecase.
Next up
- automate script using orchestration (ie ansible)
- deploy using aws code deploy
- CI / CD pipeline from github
- tighting security with firewall policies
- monitoring
- load management / balancing
Originally published on bcd.dev
以上是在您自己的伺服器上設定 Laravel:DIY 指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在PHP中,應使用password_hash和password_verify函數實現安全的密碼哈希處理,不應使用MD5或SHA1。1)password_hash生成包含鹽值的哈希,增強安全性。 2)password_verify驗證密碼,通過比較哈希值確保安全。 3)MD5和SHA1易受攻擊且缺乏鹽值,不適合現代密碼安全。

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

PHP在現代化進程中仍然重要,因為它支持大量網站和應用,並通過框架適應開發需求。 1.PHP7提升了性能並引入了新功能。 2.現代框架如Laravel、Symfony和CodeIgniter簡化開發,提高代碼質量。 3.性能優化和最佳實踐進一步提升應用效率。

PHP的核心優勢包括易於學習、強大的web開發支持、豐富的庫和框架、高性能和可擴展性、跨平台兼容性以及成本效益高。 1)易於學習和使用,適合初學者;2)與web服務器集成好,支持多種數據庫;3)擁有如Laravel等強大框架;4)通過優化可實現高性能;5)支持多種操作系統;6)開源,降低開發成本。

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
