Search code examples
regexapache.htaccessmod-rewritehttp-redirect

how to remove folder name from url using htaccess


I want to change the URL from:

http://example.com/Portfolios/iPhone/app

To:

http://example.com/iPhone/app

And same for all URLs like:

example.com/Portfolios/iPad/app

To:

example.com/iPad/app

And from:

example.com/Portfolios/xyz/app

To:

example.com/xyz/app

I have tried a lot but nothing is working for me.


<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule ^Portfolios(/.*|)$ $1 [L,NC]  
</IfModule>

Solution

  • Enable mod_rewrite and .htaccess through Apache config and then put this code in your .htaccess under DOCUMENT_ROOT directory:

    RewriteEngine On
    
    RewriteRule ^Portfolios/(.*)$ /$1 [L,NC,R=302]
    

    Explanation: Above rule is matching URL pattern that starts with Portfolios and have somthing like /Portfolios/xyz/app and puts xyz/app in $1. It makes an external redirection to /$1 i.e. /xyz/app.

    These are the flags used:

    L  - Last Rule
    NC - Ignore (No) Case comparison
    R  - External redirection (with 302)
    

    Once you verify it is working fine, replace R=302 to R=301. Avoid using R=301 (Permanent Redirect) while testing your mod_rewrite rules.