Reputation: 25
On my application i have a webshop with multiple items. For each item you are able to have different kind of colors. So the colors have to be in the url to send it as a parameter.
The moment you click on an item, you will get send to that item's page with the url http://cmsproject.local/item/2/nocolor. The nocolor is the thing i want to hide from the url, which would result looking something like this: http://cmsproject.local/item/2.
If you have selected a color the last part of the url looks this "/2136c7". This is not a problem and should still be looking like this. Only when there is no color selected, the url should hide the nocolor part.
I have tried multiple forums, but none of them worked out for me. I have tried something like this: RewriteRule ^2/nocolor/(.*)$ $1. and this RewriteRule ^/2/nocolor [L].
My htaccess file looks like this:
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]
RewriteRule ^/2/nocolor [L]
With this I expected that the url would "hide" the nocolor part, instead nothing changed and it didn't displayed any error.
Upvotes: 1
Views: 535
Reputation: 44526
If I understand your requirements correctly, I don't think you necessarily need to be handling this at the HTTP server level. From what I understand, you want a URL which can have an optional parameter as part of it.
Based on your example, my assumption is that the URL (with or without a color present) is handled by the same endpoint. So my suggestion is that you delegate that responsibility to the Laravel Router via optional route parameters.
Here's an example of how you could handle that, showcased with a simple route closure (this can of course be a controller action method):
Route::get('item/{id}/{color?}', function ($id, $color = null) {
// If the URL is "/items/2" then $color will be null
// If the URL is "/items/2/2136c7" then $color will be '2136c7'
});
Using the example above you can handle both situations.
Upvotes: 1
Reputation: 2364
You should do this in your laravel app, but in htaccess would the solution look like this:
RewriteRule ^/item/([0-9]+)/? /item/$1/nocolor
^
start of the match?
optional+
at least one occurenceTake look at RegEx for further uderstanding.
Upvotes: 0