I have developed a project with Vuejs as the front-end and Laravel as the back-end api.In localhost they run in different ports.How should I deploy them in production?
When you build your Vue app for production, all the relevant files are in the dist
folder. It does not run on any port, but instead the files are served by a webserver (e.g. Apache or Nginx). For a laravel api you normally have the public
folder in the laravel installation visible, while having the rest of the files not directly accessible from the web.
I am going to assume that you want to deploy the api and the frontend on the same domain. The easiest way of getting this to work is by having a specific prefix for your api. In the case below, I use the prefix /api
for all api requests, since this is the default for api routes. Anything else is considered a request for the frontend.
You set up your folder structure like the following. The public_html
folder is what is normally loaded when going to example.com
and you can test this by adding a test.txt
file with some content and going to example.com/test.txt
. The backend
folder contains your laravel installation. The frontend
folder contains everything that the dist
folder contained after running npm run build
.
/var
+-- /www
+-- /vhosts
+-- /example.com
+-- public_html
+-- /backend
+-- /frontend
To get everything to work, we are going to remove the public_html
folder and replace it with a symlink to backend/public
.
cd /var/www/vhosts/example.com
rm -r public_html
ln -s ../backend/public public_html
When we check example.com
, we now should see that we can make requests to the api using example.com/api/someroute
. There are several ways we can make the frontend work with this, but for ease of deployment, lets create a symlink to the dist folder.
cd /var/www/vhosts/example.com/public_html
ln -s ../../frontend/dist app
If you are using hash mode for your Vue application and don't mind accessing the app through example.com/app
, I believe this is all you would need to do. Otherwise you would need to modify the .htaccess
file if you are using Apache, or change the rewrite configuration of whatever other webserver you are using. I imagine the .htaccess
file would look something like this:
# We assume that the FollowSymLinks option is enabled in the main Apache configuration.
RewriteEngine On
# Rewrite anything that starts with `api` to the laravel index file
RewriteCond %{REQUEST_URI} ^/api
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Rewrite anything else to the frontend app
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /app/index.html [L]