Effortlessly Deploy Laravel Apps to Shared Hosting: A Beginner’s Guide
Deploying a Laravel application shouldn’t be a daunting task, even if you’re using shared hosting. This beginner’s guide will walk you through the process of deploying your Laravel application to shared hosting, making the entire process as effortless as possible. Many developers are unsure how to proceed, but with the right steps, you can have your application live in no time. We’ll cover everything from preparing your application to uploading it to the server and configuring the environment. If you are looking for even more assistance with your laravel projects, feel free to visit our laravel guide.
Why Choose Shared Hosting for Laravel?
Shared hosting is a popular choice for beginners and smaller projects due to its affordability and ease of use. While it may not offer the same level of control as VPS or dedicated servers, it provides a simple and cost-effective way to get your Laravel application online. Understanding the limitations and working within them is key to a successful deployment.
Prerequisites
Before we begin, ensure you have the following:
- A fully functional Laravel application on your local machine.
- Access to a shared hosting account with FTP access and a control panel (cPanel, Plesk, etc.).
- A text editor to modify files.
Step 1: Prepare Your Laravel Application
The first step is to prepare your Laravel application for deployment. This involves making a few modifications to ensure compatibility with the shared hosting environment.
1.1 Configure the .env File
The `.env` file contains sensitive information, such as database credentials and API keys. You’ll need to update these values to match your shared hosting environment. Obtain the database hostname, username, password, and database name from your hosting provider’s control panel. Then, update the `.env` file accordingly:
APP_NAME=Laravel
APP_ENV=production
APP_KEY=YourApplicationKey
APP_DEBUG=false
APP_URL=https://yourdomain.com
DB_CONNECTION=mysql
DB_HOST=your_database_hostname
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
Make sure to replace `your_database_hostname`, `your_database_name`, `your_database_username`, and `your_database_password` with the actual values provided by your hosting provider. Also, set `APP_URL` to your domain name (e.g., `https://yourdomain.com`) and `APP_DEBUG` to `false` for production.
1.2 Move Files to Public Directory
Shared hosting environments typically have a `public_html` or `httpdocs` directory that serves as the document root for your website. To deploy your Laravel application, you need to move the contents of the `public` directory in your Laravel project to this root directory.
Create a new directory (e.g., `laravel_app`) in your shared hosting account using the file manager in your control panel. Then, move all the files and folders except the `public` directory into this new directory.
Next, move the contents of your local Laravel project’s `public` directory to the `public_html` or `httpdocs` directory (or whatever your shared hosting’s web root is). This includes `index.php`, `.htaccess`, and any assets like CSS, JavaScript, and images.
1.3 Update the index.php File
The `index.php` file needs to be updated to point to the correct autoloader and application bootstrap files. Open `public_html/index.php` in your text editor and modify the following lines:
require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
Change them to:
require __DIR__.'/laravel_app/vendor/autoload.php';
$app = require_once __DIR__.'/laravel_app/bootstrap/app.php';
Replace `laravel_app` with the name of the directory you created in the previous step.
1.4 Configure .htaccess (if needed)
Ensure that you have a `.htaccess` file in your `public_html` directory. If you don’t have one, create a new file named `.htaccess` and add the following content:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule . - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
This file ensures that all requests are routed through the `index.php` file, allowing Laravel to handle the routing.
Step 2: Upload Your Application to Shared Hosting
Now that you’ve prepared your application, it’s time to upload it to your shared hosting account. Use an FTP client like FileZilla or Cyberduck to connect to your server using the credentials provided by your hosting provider. If you need even more assistance with web hosting, this Toronto web hosting guide may be useful.
- Connect to your server using your FTP client.
- Navigate to the directory where you created the `laravel_app` directory (one level above `public_html`).
- Upload all the files and folders from your local Laravel project (except the `public` directory) to this directory.
Step 3: Set Up Your Database
Next, you need to create a database and import your application’s database schema. Follow these steps:
- Log in to your hosting provider’s control panel (cPanel, Plesk, etc.).
- Navigate to the database section (usually MySQL Databases or similar).
- Create a new database, user, and grant the user all privileges to the database.
- Import your database schema using phpMyAdmin or a similar tool. You can export your database schema from your local development environment using `php artisan migrate:fresh –seed` or a database management tool like DBeaver.
Step 4: Configure the Application Key
The application key is used for encrypting data and ensuring security. If you haven’t already, you need to generate a new application key and set it in your `.env` file on the server. However, since you’re on shared hosting and might not have SSH access, you’ll need to do this through the web interface.
Add the following lines to the top of your `public/index.php` file:
<?php
use IlluminateSupportFacadesArtisan;
require __DIR__.'/laravel_app/vendor/autoload.php';
$app = require_once __DIR__.'/laravel_app/bootstrap/app.php';
if (empty(env('APP_KEY'))) {
Artisan::call('key:generate');
echo '<h1>Application key generated. Please remove these lines from public/index.php immediately!</h1>';
die();
}
Visit your website in the browser. Laravel will generate the key and display it on the screen. Copy the generated key, and then immediately remove the code from `public/index.php`. Then, edit the `.env` file directly via the hosting provider’s file manager, adding `APP_KEY=your_generated_key`.
Step 5: Set File Permissions
Ensure that the `storage` and `bootstrap/cache` directories have the correct permissions to allow Laravel to write to them. Typically, this means setting the permissions to `775` or `777`, but it’s recommended to use the most restrictive permissions that still allow the application to function correctly. Consult your hosting provider’s documentation for best practices.
You can use your FTP client or the file manager in your control panel to change the file permissions. Right-click on the directory, select ‘File Permissions’ or ‘Change Permissions’, and enter the desired permissions.
Step 6: Test Your Application
Finally, it’s time to test your application. Visit your website in your browser and verify that everything is working as expected. Check the following:
- Database connectivity
- Routing and navigation
- Form submissions
- File uploads (if applicable)
If you encounter any errors, check the Laravel log files in the `storage/logs` directory for more information. You may need to enable error logging in your `.env` file by setting `APP_DEBUG` to `true` temporarily, but remember to set it back to `false` once you’ve resolved the issue.
Common Issues and Troubleshooting
- 500 Internal Server Error: Check your `.htaccess` file and ensure that mod_rewrite is enabled. Also, verify that your PHP version is compatible with Laravel.
- Database Connection Errors: Double-check your database credentials in the `.env` file.
- File Permission Issues: Ensure that the `storage` and `bootstrap/cache` directories are writable.
- Routing Issues: Verify that your `.htaccess` file is correctly configured and that your routes are defined correctly in your Laravel application.
Optimizing for Shared Hosting
To optimize your Laravel application for shared hosting, consider the following:
- Caching: Utilize Laravel’s caching mechanisms to reduce database queries and improve performance.
- Queues: Offload long-running tasks to queues to prevent blocking the main request thread.
- Optimize Assets: Minify CSS and JavaScript files to reduce page load times.
- Use a CDN: Consider using a Content Delivery Network (CDN) to serve static assets from multiple locations, improving performance for users around the world. You may also find our guide to using git for version control helpful for making sure your updates are accurate.
Conclusion
Deploying a Laravel application to shared hosting doesn’t have to be a complex process. By following these steps, you can effortlessly deploy your application and get it online quickly and easily. Remember to configure your `.env` file, move the necessary files to the correct directories, set up your database, and test your application thoroughly. While shared hosting has limitations, it can be a great starting point for smaller Laravel projects. Consider exploring the power of laravel for scalable applications.
For more detailed information and advanced configurations, you can refer to the official Laravel documentation: Laravel Deployment Documentation. And if you’re looking for more general advice on web hosting configuration, you can find helpful articles at SiteGround’s Laravel on Shared Hosting tutorial.