Skip to content

Instantly share code, notes, and snippets.

@ux-powered
Created May 25, 2020 09:33
Show Gist options
  • Save ux-powered/ff8762ca771e527eaf53518781e20d07 to your computer and use it in GitHub Desktop.
Save ux-powered/ff8762ca771e527eaf53518781e20d07 to your computer and use it in GitHub Desktop.
Deploy a Laravel project to a subdirectory

The guide how to deploy a Laravel project to a subdirectory.

Let's assume we want to deploy our laravel-demo app to http://example.com/laravel_demo/. Here's what you will need to do:

  1. Add the next key to your .env config:
ASSET_URL=
  1. Create .env.production with the next content:
APP_URL=http://example.com/laravel_demo
ASSET_URL=/laravel_demo

Note: APP_URL and ASSET_URL keys mustn't have a / at the end!

  1. Open webpack.mix.js and update configs:
mix.options({
    resourceRoot: `${process.env.ASSET_URL}/`
});
mix.webpackConfig({
    output: {
        publicPath: `${process.env.ASSET_URL}/`,
        ...
    },
    ...
});
  1. Open config/app.php and add the next config key:
return [
    'mix_url' => env('ASSET_URL', null),
    ...
]
  1. All images must be included with the asset() helper:
<!-- Before -->
<img src="/img/avatars/1.png">

<!-- After -->
<img src="{{ asset('/img/avatars/1.png') }}">
  1. Open routes/web.php and change the first redirection route:
Route::redirect('/', 'dashboards/dashboard-1', 301);
  1. To have access to the current site location in your JS scripts, add the next code in your resources/views/layouts/application.blade.php:
<script>
    window.ASSET_URL = "{{ config('app.asset_url') }}";
</script>
  1. Upload the project to the subdirectory in the document root of your remote server. For example, I uploaded the project to /usr/local/htdocs/laravel-demo/.

  2. Configure your server. My Nginx config:

location /laravel_demo {
    alias /usr/local/htdocs/laravel-demo;
    index index.html index.htm index.php;
    try_files $uri $uri/ @laravel_demo;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    charset utf-8;

    error_page 404 /index.php;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
}

location @laravel_demo {
    rewrite ^/laravel_demo/(.*)$ /laravel_demo/index.php?/$1 last;
}

Apache config:

Alias /laravel-demo/ /usr/local/htdocs/laravel-demo/public/
<Directory "/usr/local/htdocs/laravel-demo/public/">
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Require all granted
</Directory>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment