skip to Main Content

For SEO i need create URL in the form of uppercase or lowercase.

For example (Original URL):

https://example.com/CATEGORY/product

If user run this URL:

https://example.com/category/product or https://example.com/CATEGORY/PRODUCT

Converto to:

https://example.com/CATEGORY/product

How to create this URL in web.php ?

2

Answers


  1. Something like this will work (I’m making assumptions about what you are using category and product params for.

    Route::get('{category}/{product}', function($category, $product) 
    {
        $product = Product::where('product_title', strtolower($product))
            ->and('category', strtolower($category))
            ->get();
    
        return $product;
    });
    

    Key points:

    • The router doesn’t care if its uppercase or lowercase
    • You, need to establish how to convert from one case to the other – in the above example, I just converted to lower case (but you may need to use studley case, kebab case, etc (checkout the Laravel helpers part of the docs)).
    Login or Signup to reply.
  2. If I understand your specific question correctly, you want to redirect users to
    https://example.com/CATEGORY/product
    if they hit any url that contains the same characters but use different capitalization, such as
    https://example.com/category/product

    This kind of redirect could be handled by adding redirect logic to the route in @Chris answer.

    Route::get('{category}/{product}', function($category, $product) 
    {
        if(strtoupper($category) != $category || strtolower($product) != $product) {
            return redirect(strtoupper($category).'/'.strtolower($product));
        }
    
        $product = Product::where('product_title', strtolower($product))
            ->and('category', strtolower($category))
            ->get();
    
        return $product;
    });
    

    Laravel returns a 302 code by default, which indicates a temporary redirect. This is because it is much better to accidentally send a temporary redirect than to accidentally send a permanent one. In this case, it sounds like you might want to make it permanent, so add the return code to your redirect call.

    return redirect(strtoupper($category).'/'.strtolower($product), 301);
    

    That way their browser will remember to always the route you want. It will also indicate to search engines to index the correct url.

    Unlike Apache, Nginx urls are case-sensitive. This is to improve performance. Laravel routes are also case-sensitive. So if you are using a Laravel + Nginx stack then you have to consider case in all your routes. You could handle redirects in the Nginx configuration, but in this case matching on http://example.com// could easily catch urls you didn’t intend to.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search