zookastos
zookastos

Reputation: 935

URL Rewriting Add a folder name to URLs

I have an apache2 server.

My directory structure is - (below is inside - /some-folder/abc)

- app
  - otherfolder
  - pqr.php
  - xyz.php
- js
- css

.htaccess is placed inside /some-folder/abc

Context root for virtual host is set till - /some-folder/

Now, I want my users to enter this URL - http://someserver.com/abc/xyz or http://someserver.com/abc/pqr

I want to open the page at - http://someserver.com/abc/app/xyz.php or http://someserver.com/abc/app/pqr.php

How can I achieve this using URL Rewriting mod_rewrite

This is what I have so far, which is not working -

Options +FollowSymLinks -MultiViews
#Turn mod_rewrite on
RewriteEngine On
#RewriteBase /abc

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ /app/$1\.php [L] # this doesn't work either
# RewriteRule ^(.*)$ app/$1.php [L] # this doesn't work either
# RewriteRule ^abc/(.*)$ abc/app/$1.php [L] # this doesn't work either

Thank you for your help.

If possible, I would also like to take all query params using forward slash ex - http://someserver.com/abc/app/xyz.php/xId/123/uId/938/sdh/8374 instead of http://someserver.com/abc/app/xyz.php?xId=123?uId=938?sdh=8374

There is no pattern for query params, they can be anything for an page. Is this possible by a generic mod_rewrite, or do I have to rewrite urls for each page, and each time my developers add a new query param?

Upvotes: 1

Views: 520

Answers (1)

anubhava
anubhava

Reputation: 785128

This rule should work for you from /abc/.htaccess:

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/abc/app/$1.php -f
RewriteRule ^(?!internal)(.+?)/?$ app/$1.php [L,NC]
  • RewriteCond makes sure that we have a corresponding .php file in /abc/app/ sub-directory.
  • (?!internal) is negative lookahead assertion to skip internal from this rewrite.

Also it appears you're using a relative URL for css/js/images e.g. src="abc.png" and your current URL is: /abc/xyz then browser resolves this relative URL to http://example.com/abc/xyz/abc.png which obviously will cause a 404 since your static files are residing in /abc/app/ sub-directory.

You can add this just below <head> section of your page's HTML:

<base href="/abc/app/" />

so that every relative URL is resolved from that base URL and not from the current page's URL.

Also as a practice to use absolute links instead of relative ones change relative link <a href="xyz">XYZ</a>, to this one <a href="/abc/xyz">XYZ</a>

Upvotes: 1

Related Questions