Adding a Rewrite rule to my PHP code - php

I could not find a satisfying answer nowhere, and i know very basics about Rewrite Rules, but just can't find a way to achieve that. I would like to clip a certain portion of my address:
/entry.php?id=howdy-world
so, I would like it to look like this:
/entry/howdy-world/
I know how to point to a default file, or Rewrite get values to become numbers after the trailing slash, but the portion to be trimmed is kind of in the middle. How to deal with that?

Below is the basic syntax of how to forward from one url to another. The below has a few sections
([^/] +): This matches any character multiple times up to a slash. ex: entry/howdy-world/
$1: This would take what was after entry/ and append it to the required url. ex: entry.php?id=howdy-world
More information on rewriting can be found on the Apache website
RewriteEngine On
RewriteRule ^entry/([^/]+)$ entry.php?id=$1 [L]
# Variations of above rule depending on server setup
# RewriteRule ^entry/(.+)$ /entry.php?id=$1 [L]
# RewriteRule ^entry/(.+)$ http://www.example.com/entry.php?id=$1 [L]

Related

Removing the query string and redirecting (rewrite rule and rewrite cond)

I am currently trying to set up a rewrite rule to set up an internal redirect for a more SEO-friendly url-structure.
I want to show:
/find-teacher/primary-school.php
instead of the sad looking:
/find-teacher/subject-class-choose.php?school=primary-school
After I read some posts and tutorials about the rewrite rule and rewrite cond, I came up with this:
In my choose-school.php I have as a link with the nice looking url:
<a href="https://www.example.com/find-teacher/primary-school.php">
Primary School</a>
In my .htaccess:
RewriteCond %{REQUEST_URI} ^find-teacher/primary-school.php$
RewriteRule ^find-teacher/([a-z-]+)-([0-9]+).php$ /find-teacher/subject-class-choose.php?school=$1 [NC]
Now if I got that right, the RewriteCond part checks if the following url is requested. If that is the case, then the part of ([a-z-]+)-([0-9]+) is replaced by the $1 of the substitution part (/find-teacher/subject-class-choose.php?school=$1)
Problem is that I am redirected to my error page if I click on /find-teacher/primary-school.php
You don't need both a RewriteCond and a RewriteRule here, because they are (or should be) both checking the same thing.
However, currently, there is no URL which will match both patterns. Let's break down the problem.
To check specifically for the URL /find-teacher/primary-school.php, you could just write:
RewriteRule ^find-teacher/primary-school.php$ /find-teacher/subject-class-choose.php?school=primary-school [NC]
The next step is to "capture" the "primary-school" with ( and ), and place it dynamically onto the target with $1:
RewriteRule ^find-teacher/(primary-school).php$ /find-teacher/subject-class-choose.php?school=$1 [NC]
Finally, we can make the pattern match any letters or hyphens instead of an exact string, using the regex [a-z-]+:
RewriteRule ^find-teacher/([a-z-]+).php$ /find-teacher/subject-class-choose.php?school=$1 [NC]
In the rule in your question, you've added an extra part to the regex: -([0-9]+). This matches - and then a number. To capture that number, you'd put $2 somewhere in your target:
RewriteRule ^find-teacher/([a-z-]+)-([0-9]+).php$ /find-teacher/subject-class-choose.php?school=$1&id=$2 [NC]
This would match something like /find-teacher/primary-school-123.php, and turn it into /find-teacher/subject-class-choose.php?school=primary-school&id=123.
Two final notes:
depending how your Apache configuration is set up, you may or may not need to include the leading / in your patterns, i.e. start them with ^/
I find a nice way to debug rewrite rules is to make them redirect your browser, by adding R=temp to the flags (e.g. [NC,R=temp]); that way, you don't have to rely on your PHP code to tell you what URL was requested

To Explode or RewriteRule? Utilizing Variables From Hyphenated URL's

I'm hoping I can make this make sense.
I had URLs' that looked like this
http://www.website.com/state/AZ/Phoenix
And now I've written them to this
http://www.website.com/AZ
using this rewrite code to parse (borrowed)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/.]+)(?:/)?$ /x.php?state=$1 [L]
RewriteRule ^([^/.]+)/([^/.]+)(?:/)?$ /x.php?state=$v1 [L]
RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)(?:/.*)?$ /x.php?state=$1&city=$2 [L]
This works great for parsing the "AZ" portion of the url and using it as a variable. Awesome. However, I wanted to take this to the next step and start using the city, and even crazier? not in the same order.
DESIRED URL FORMAT: http://www.website.com/phoenix-arizona-other-words
NOTE: I understand this doesn't say "AZ", it's fine, I'll convert the state to abbreviation through an array - the more important part is grabbing the first two words, separated by a hyphen and assigning them to variables.
For my code to work correctly I'll need to either find a way to explode the "-" in the URL and assign variables this way...
//my terrible attempt at fixing this the HARD way
$variables = explode("-", urldecode(substr($_SERVER['REQUEST_URI'], 1)));
$city = isset($variables[1]) ? $variables[1] : false;
$state = isset($variables[2]) ? $variables[2] : false;
or...
A RewriteRule could possibly save the day and understand what to do with the newly formatted URL and allow x.php? to utilize the correct variables, all while keeping the desired website.com/phoenix-arizona structure.
I think I'm close, basically, I need a Rewriterule to recognize hyphens and assign them to specific parameters, however I've been searching and tinkering around for over 4 hours on this before finally giving in! Any help would be appreciated, and if I'm not thinking about this correctly, it wouldn't surprise me as it's quite clear my regex (RewriteRule) skills are rudimentary at best and the explode function, if it even works, might be total overkill.
This rule should work to translate your PHP code into a rewrite rule:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^-]+)-([^/-]+)-(.+)$ /x.php?state=$1&city=$2 [L,QSA]
ok. I'll try to complete this answer tomorrow. But for the first rule, you might try with
RewriteRule ^([A-Z]){2}/? /x.php?state=$1& [L,QSA]
This means: match exactly two uppercase characters from A to Z, followed by an optional trailing slash and whatever comes next
This will turn
http://www.website.com/AZ
into
http://www.website.com/x.php?state=AZ
AND
http://www.website.com/AZ/whatever-url
into
http://www.website.com/x.php?state=AZ&whatever-url
Note that I have appended #anubhava QSA flag to append any query string after the slash to the rewrite rule. I could have captured that part with a wildcard (.*) too. I like his way more than mine.
States are easy because thanks to the USPS they all have kinda standard two character codes.
Edit: now for the second rule
RewriteRule ^([^-]+)-([^/-]+)- /x.php?statelong=$2&city=$1& [L,QSA]
will turn
http://www.domain.com/tucson-arizona-whatever-comes-next
into
http://www.domain.com/x.php?statelong=arizona&city=tucson&whatever-comes-next
Note that I inversed the captured items so I pass the second one to statelong. This way on your PHP you'll know that the state name needs to go through your dictionary array to get its standard USPS 2 character code.
Again, the "whatever comes next" gets appended thanks to the QSA flag. You'll need to capture that part with php by printing out the $_GET superglobal and looking for the orfan key.
Now, what happens when you get
http://www.domain.com/new-york-new-york-these-vagabond-shoes
Of course the rule won't work. Besides, the song was written when there was a New York County, roughly equivalent to today's Manhattan. (Irrelevant trivia).
The next is just an idea. I'm sure you can come with a more creative way
You need a way to tell cities from states from rest of the url. One way to do it is to use underscores to separate composite names, comma to separate city from state and hyphen for the rest.
This rule
RewriteRule ^([\w_]+),([\w_]+)- /x.php?statelong=$2&city=$1& [L,QSA]
will turn
http://www.domain.com/new_york,new_york-this-vagabond-shoes
to
http://www.domain.com/x.php?statelong=new_york&city=new_york&this-vagabond-shoes

URL Rewrite with htaccess and PHP

I have a URL: search/?word=asdf and want to redirect to: search/word/asdf/ and running internally: ?cmd=search&word=asdf
This so you can get the PHP $ _GET ['cmd'] and $ _GET ['word'].
How to do it in htaccess?
EDIT:
My .htaccess now is:
RewriteRule search(.*) %{HTTP_REFERER}cmd/search$1
RewriteRule cmd/search/?key-word=(.*) %{HTTP_REFERER}cmd/search/key-word/$1
But this not working. The new URL ever is:
localhost/bruc/sandbox/electrolux/trunk/cmd/search/?key-word=asdf
But it should be: localhost/bruc/sandbox/electrolux/trunk/cmd/search/key-word/asdf
So, I redirect this correct URL to: localhost/bruc/sandbox/electrolux/trunk/?cmd=search&key-word=asdf
But not working fine! Try, my approach here: http://htaccess.madewithlove.be/
Try RewriteRule ^([^/]*)/word/([^/]*)$ /?cmd=$1&word=$2 [L]. I believe that will accomplish your goal.
Try this :
RewriteEngine on
RewriteRule ^search/word/(.*)$ /?cmd=search&word=$1 [L]
Check this.
RewriteEngine on
RewriteRule ^([^/]+)/([^/]+)/([^/]+) /?cmd=$1&word=$2 [L]
There are three parts to this:
RewriteRule specifies that this is a rule for rewriting (as opposed to a condition or some other directive). The command is to rewrite part 2 into part 3.
This part is a regex, and the rule will be run only if the URL matches this regex. In this case, it says - look for the beginning of the string, then a bunch of non-slash characters, then a slash, then another bunch of non-slash characters. then again bunch of non-slash characters, then a slash, then another bunch of non-slash characters. The parentheses mean the parts within the parentheses will be stored for future reference.
Finally, this part says to rewrite the given URL in this format. $1 and $2 refer to the parts that were captured and stored.

Trouble with URL rewriting in .htaccess

My .htaccess file looks like this:
RewriteEngine On
RewriteRule ^articles/(\d+)*$ ./articles.php?id=$1
So, if the URL foo.com/articles/123 is requested, control is transferred to articles.php?id=123.
However, if the requested URL is:
foo.com/articles/123/
or
foo.com/articles/123/whatever
I get a "404 Not Found" response.
I would like to call articles.php?id=123 in all these cases. So, if the URL starts with foo.com/articles/[digits]... no matter what other characters follow the digits, I would like to execute articles.php?id=[digits]. (The rest of the URL is discarded.)
How do I have to change the regular expression in order to achieve this?
Just don't look for the end:
RewriteRule ^articles/(\d+) ./articles.php?id=$1
You do need to allow the trailing / with:
RewriteRule ^articles/(\d+)/?$
The \d+ will only match decimals. And the $ would disallow matches beyond the end.
If you also need trailing identifiers, then you need to allow them too. Then it might be best to make the match unspecific:
RewriteRule ^articles/(.+)$
Here .+ matches virtually anything.
But if you want to keep the numeric id separate then combine those two options:
RewriteRule ^articles/(\d+)(/.*)?$ ./articles.php?id=$1

What is wrong with this URL rewrite?

I want (for example)
discuss/1/title/where-are-you
to output
discussPage.php?id=1&title=where-are-you
I have the following commands in a .htaccess file which is in the same directory as discussPage.php:
# Enable Rewriting
RewriteEngine on
# Rewrite user URLs
# Input: discuss/ID/title/TITLE
# Output: discussPage.php?tid=NAME&title=TITLE
RewriteRule ^discuss/(\w+)/(\w+)/(\w+)/?$ discussPage.php?id=$1&title=$3
Right now I am getting a 404 error when I try to visit a page like discuss/1/title/where-are-you even though discussPage.php?id=1&title=where-are-you works fine.
P.S. mod_rewrite is enabled (i have used it for other purposes).
Your problem is that \w does not match the "-" in the last bit.
You can simply allow dashes in there using a broader character class like [\w-]+. I would be careful with solutions like [^/] because they allow anything except a slash, which is quite permissive. White-lists are always safer and avoid surprises.
# Enable Rewriting
RewriteEngine on
# Rewrite user URLs
# Input: discuss/ID/title/TITLE
# Output: discussPage.php?tid=NAME&title=TITLE
RewriteRule ^discuss/(\w+)/(\w+)/([\w-]+)/?$ discussPage.php?id=$1&title=$3
Note that the - has to be last in the character class, otherwise you should escape it, because if it's in between two other characters it behaves as a range, like in [a-z].
To debug, you can always echo $_SERVER['QUERY_STRING'];
But I believe the correct code would be something like this.
RewriteEngine on
RewriteBase /
RewriteRule ^discuss/([0-9]+)/title/([a-z0-9\-]+)?$ discussPage.php?id=$1&title=$2 [NC,QSA]
You might want to fix your RewriteBase value, though.
Also - as seen in the last condition, you can only have alphanumeric characters and hyphens in the where-are-you part. (but something tells me you won't be needing other characters!)
Works for me:
RewriteEngine On
RewriteBase /
RewriteRule ^discuss/([^/]+)/([^/]+)/([^/]+)/?$ discussPage.php?id=$1&title=$3 [R]

Categories