sam
sam

Reputation: 1087

mod rewrite to remove the file name from url

If I have a file, let's say rec-view.php, then I can call it by this URL:

domain.com/record/rec-view.php?id=3

However, I want to call this file with the following URL as well:

domain.com/record/3

So, basically I want to tell the server that if there is any file that ends with the "-view.php" name, then it should remove the file name all together in the URL and open that file only by passing the id.

I am trying the following rule, it accesses the file by "/v" but I need to access by the dynamic number.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)/v$ $1-view.php [NC,L]

Upvotes: 0

Views: 1608

Answers (2)

Hassaan
Hassaan

Reputation: 7662

Try:

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^(.*)/(.*) $1-view.php?id=$2 [L]

Upvotes: 1

sepehr
sepehr

Reputation: 18445

Try this:

Options +FollowSymLinks

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    # Match the host, if you wish
    #RewriteCond %{HTTP_HOST} ^domain\.com$

    RewriteRule record/(\d) /record/rec-view.php?id=$1 [NC,L]
</IfModule>

You can test it online, if you wish.

enter image description here

With (\d) you're only matching against numeric values, if you wish to accept any values, you may change it to (.*).

Just saw that you need a more generic rule:

# Maps record/4 to record/record-view.php?id=4
RewriteRule (.*)/(\d) /$1/$1-view.php?id=$2 [NC,L]

For this to work, you need a more strict naming convention in place. More specifically, you need all those *-view.php files to be named exactly like their containing directory.

There's no way to get rec prefix out of thin air unless it's always the first 3 characters; is it?

Update

As per your comment, here's a more generic ruleset that checks if the URI's last segment is a number and if so, then it maps the request to the containing directory's *-view.php file while maintaining the directory structure and appending the ?id=* query string:

# This rule maps this:
#     domain.com/foo/bar/baz/4 
# to: 
#     domain.com/foo/bar/baz/baz-view.php?id=4
RewriteRule ^(.*)/(.*)/(\d)$ /$1/$2/$2-view.php?id=$3 [L,R]

There are other variations that you might have wanted:

# This rule maps this:
#     domain.com/foo/bar/baz/4 
# to: 
#     domain.com/foo/bar/baz-view.php?id=4
#
# Notice the baz/ segment dropped.
RewriteRule ^(.*)/(.*)/(\d)$ /$1/$2-view.php?id=$3 [L,R]

# This rule maps this:
#     domain.com/foo/bar/baz/4 
# to: 
#     domain.com/baz-view.php?id=4
#
# Notice all the segments dropped. Mapping to 
# a php file in the root directory. 
RewriteRule ^(.*)/(.*)/(\d)$ /$2-view.php?id=$3 [L,R]

Upvotes: 1

Related Questions