Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Gridsome Rewrite Rules for Dynamic Routes After Build

Last modified on December 8, 2019 51 sec read

In this article, I’m going to share how to rewrite rules for the dynamic routes after publishing Gridsome application on live server.

Table of Contents

  1. Create Dynamic Pages
  2. Rewrite Rules for Apache
  3. Rewrite Rules for Nginx
  4. Rewrite Rules for Netlify

Step 1 : Create Dynamic Pages

Let’s create three dynamic pages using the Pages API. Here’s an example:

gridsome.server.js
module.exports = function (api) {
    api.createPages(({createPage}) => {
        createPage({
            path: '/products/:slug',
            component: './src/templates/Product.vue'
        })
        createPage({
            path: '/categories/:slug',
            component: './src/templates/Category.vue'
        })
        createPage({
            path: '/shops/:slug',
            component: './src/templates/Shop.vue'
        })
    })
}

We’ve created the dynamic pages. Now we need to set rewrite rules to work the page’s routes on live server.

Step 2 : Rewrite Rules for Apache

On the root directory of your server, create a file called .htaccess and then open & paste the rules:

RewriteEngine On

RewriteRule ^products/([^/]*)$ products/_slug.html [NC,L]
RewriteRule ^shops/([^/]*)$ shops/_slug.html [NC,L]
RewriteRule ^categories/([^/]*)$ categories/_slug.html [NC,L]

Step 3 : Rewrite Rules for Nginx

In the Nginx configuration file, write rules like these:

location /products {
  rewrite ^/products/([^/]*)$ /products/_slug.html break;
}
location /shops {
  rewrite ^/shops/([^/]*)$ /shops/_slug.html break;
}
location /categories {
  rewrite ^/categories/([^/]*)$ /categories/_slug.html break;
}

Step 4 : Rewrite Rules for Netlify

Go to the static folder and create a file called “_redirects“. Then write rules like these:

/products/* /products/_slug.html 200
/shops/* /shops/_slug.html 200
/categories/* /categories/_slug.html 200
The article is over. Thanks for reading. 🙂

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Leave a Reply

Your email address will not be published. Required fields are marked *