8

Mod rewrite to delete the file name of the url

 3 years ago
source link: https://www.codesd.com/item/mod-rewrite-to-delete-the-file-name-of-the-url.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Mod rewrite to delete the file name of the url

advertisements

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]


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.

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]




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK