简体   繁体   中英

URL Rewrite Regular Expression to suit all

Brief Explanation

I am trying to come up with a smart way of controlling my web page rewrites with as few rewrites as possible.

So, for example, if you have the following page translations:

'domain.com/test/'        => 'domain.com/test.php'
'domain.com/errors/404/'  => 'domain.com/errors.php?code=404' 

You could have individual rewrites for every page... However, I like to minimise this by instead having one regular expression to suit all. So the regular expression to match the above would be:

^([a-z0-9\-]+)\/?([a-z0-9\-]+)?\/?$

and then the matches would be placed into the URL like so (note that code would be replaced by request on the errors page) :

domain.com/$1.php?request=$2

and then you could append the query string...

Obviously in some cases you need individual rewrites, but you can usually minimise this by using clever regular expressions and well structured pages.

My Problem

Similar to the above example, I have pages within my site that are rewritten with this exact regular expression. So the following pages translate like so:

'domain.com/shipments/open/' => 'domain.com/shipments.php?request=open'
'domain.com/settings/user/'  => 'domain.com/settings.php?request=user'
etc...

However, for reasons which I will not go into, I also have pages written like so:

'domain.com/shipment/edit'

Notice the it says shipment not shipments ! Despite this, I still want this to be rewritten to the shipments page. So the translation would look like this:

'domain.com/shipment/edit' => 'domain.com/shipments.php?request=edit'

I cannot think of a way other than another rewrite that specifies that shipment is an alias for shipments ...

One of the reasons I do not want individual rewrites for this is that I am not just talking about shipments, there are many documents that I need to alias, and therefore would rather not go down the multiple rewrite route as my web.config file will get pretty darn large.

I have come up with the following solutions (but obviously I am not happy with them):

  1. Have a page in my root directory called shipment.php and just include the contents of shipments.php
  2. Write rewrites for each page with an alias...

I cannot think of another (better) way of doing this, can any of you?

Since you only have 1 exception, why not add that one exception ?

We will use a "rewrite rewrite technique" (I just came up with that name lol)

RewriteEngine On

RewriteRule ^([a-z0-9-]+[^s/])s*/?([a-z0-9-]+)?/?$ $1s/$2 [NC]

RewriteRule ^([a-z0-9-]+)/?([a-z0-9-]+)?/?$ $1.php?request=$2

Tested on localhost and this RewriteRuleTester .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM