1

I have a URL structure like this: example.com/this/is/nice/index.php

and I want achieve this: example.com/this/index.php

How can I add a rule to hide the /is/ and /nice/ subfolders ?

3
  • 1
    Are the folders you want hidden always '/is/nice' or is that just one example of many? Jun 21 at 0:59
  • 2
    When you say you want something "hidden", there are three parts to that. 1) Making the short URL work (show the same content as the long URL), 2) Redirect the long URL to the short URL, 3) Change all the links on the site to point to the short URL. .htaccess is good at the first, can be made to do the second, and really can't do the third at all. Which of those three do you need? Jun 21 at 1:01
  • 1
    @StephenOstermiller Yes. It's only those two /is/nice/ I need the first and second. I don't want the the option 3 at all :) Jun 21 at 11:25

1 Answer 1

2

This assumes you have already changed all the internal links on your site to be of the form /this/index.php (or /this/<something>?), ie. #3 in @Stephen's comment above.

For your specific example, you would add something like the following, using mod_rewrite, to the top of the root .htaccess file (requires Apache 2.4):

RewriteEngine On

# A) Redirect "/this/is/nice/index.php" to "/this/index.php"
RewriteRule ^(this)/is/nice/(index\.php)$ /$1/$2 [R=301,L]

# B) Rewrite "/this/index.php" to "/this/is/nice/index.php"
RewriteRule ^(this)/(index\.php)$ $1/is/nice/$2 [END]

The $1 and $2 backreferences contain the value of the corresponding captured subgroup in the preceding RewriteRule pattern (first argument). In this example, that just saves having to repeat "this" and "index.php".

For a more generic solution that rewrites /this/<anything> to /this/is/nice/<anything> (and redirects vice-versa) then use something like the following instead:

# A) Redirect "/this/is/nice/<anything>" to "/this/<anything>"
RewriteRule ^(this)/is/nice/(.*) /$1/$2 [R=301,L]

# B) Rewrite "/this/<anything>" to "/this/is/nice/<anything>"
RewriteRule ^(this)/(.*) $1/is/nice/$2 [END]

Note that this rewrites everything, including any static assets - which may or may not be a problem depending on your scenario (not stated in the question). eg. /this/images/myimage.jpg would be rewritten to /this/is/nice/images/myimage.jpg, regardless of whether /this/images/myimage.jpg exists or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.