anuj rajput
anuj rajput

Reputation: 337

url rewrite using htaccess without redirection

I have a url like this: http://www.localhost.com/code_category/computers/

I want to change this url to: http://www.localhost.com/category/computers/

I don't need url redirection. My current htaccess file looks like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Upvotes: 1

Views: 4485

Answers (2)

Sivaraj S
Sivaraj S

Reputation: 340

.htaccess file

Add this code

RewriteEngine on
RewriteCond %{HTTP_HOST} ^localhost.com [NC,OR]

# without redirect
# RewriteRule ^/code_category/computers/$ category/computers/
RewriteRule ^/category/computers/$ code_category/computers/

# redirect method
# RedirectMatch 301 ^/code_category/computers/$ category/computers/
  • RewriteEngine On enables mod_rewrite.
  • RewriteCond %{HTTP_HOST} shows which URLs we do and don't want to run through the rewrite.
    1. In this case, we want to match example.com.
    2. ! means "not." We don't want to rewrite a URL that already includes folder1, because then it would keep getting folder1 added, and it would become an infinitely long URL.
  • [NC] matches both upper- and lower-case versions of the URL.
  • RewriteRule defines a particular rule.
  • The first string of characters after RewriteRule defines what the original URL looks like. There's a more detailed explanation of the special characters at the end of this article.
  • The second string after RewriteRule defines the new URL. This is in relation to the document root (html) directory. / means the html directory itself, and subfolders can also be specified.

For Reference click here

Hope this helps!

Upvotes: 1

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

You only want to redirect code_category to categoryexternally and keep the path as it is internally so, try this :

RewriteCond %{THE_REQUEST} !\s/+category/ [NC]
RewriteRule ^code_category/(.*)$ category/$1 [R=302,L,NE]
RewriteRule ^category/(.*)$ code_category/$1 [L]

The above will redirect any request containscode_category/whatever to category/whatever externally and keep the internal path as it is .

If you want only request contains code_category/computers/ change it to this :

RewriteCond %{THE_REQUEST} !\s/+category/computers/ [NC]
RewriteRule ^code_category/computers/(.*)$ category/computers/$1 [R=302,L,NE]
RewriteRule ^category/computers/(.*)$ code_category/computers/$1 [L]

test it , if it is fine change 302 to 301 for permanent redirection.

Note: clear your browser cache then test it.

Upvotes: 1

Related Questions