Rohit
Rohit

Reputation: 207

Replacing "/" in URL querystring to avoid 404 in htaccess

I have a url which has two parameters and I have rewritten them in the htaccess file with this

RewriteRule ^subscriber/([^/.]+)/([^/.]+)/?$ subscriber/index.php?id=$1&name=$2 [NC,L]

The name in some cases contains a "/" which the browser is treating like another parameter and is giving me a 404 page. Is there a way to replace "/" to something else using the htaccess file?

Upvotes: 3

Views: 204

Answers (2)

Jon Lin
Jon Lin

Reputation: 143906

Try putting this in the htaccess file in your document root:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^(.*)name=([^&]*)/(.*)$
RewriteRule ^ %{REQUEST_URI}?%1name=%2-%3 [L]

# Change your existing rule a bit to account for the slash (plus a possible trailing slash):
RewriteRule ^subscriber/([^/.]+)/(.+?)/?$ /subscriber/index.php?id=$1&name=$2 [NC,L]

This will make the first "folder" in the URI after subscriber/, the id param, and everything after that except for a trailing slash be the name param. The first set of rules then repeatedly clean out the name param, replacing / with -.

Upvotes: 1

Mihai Matei
Mihai Matei

Reputation: 24276

You can use urlencode() function when setting the name variable

$name = 'Michael/';
$name = urlencode($name);
// will return you Michael%08 or something like this

Accordingly with this question the solution for .htaccess might be:

RewriteEngine On
RewriteCond %{REQUEST_URI} (.*)\\(.*)
RewriteRule .* %1/%2 [R=301]

Upvotes: 0

Related Questions