My goal is to make some friendly URL's using .htaccess. I need a mod_rewrite (for .htaccess) solution that allows me to have URLs like:
http://www.example.com/admin/lots -> /admin/lots/index.php
http://www.example.com/admin/lots/edit/1 -> /admin/lots/edit.php?id=1
http://www.example.com/admin/lots/view/1 -> /admin/lots/view.php?id=1
http://www.example.com/admin/lots/view/more/1 -> /admin/lots/view/more.php?id=1
http://www.example.com/admin/settings -> /admin/settings/index.php
http://www.example.com/admin/settings/edit/1 -> /admin/settings/edit.php?id=1
http://www.example.com/admin/project/status/edit/1 -> /admin/project/status/edit.php?id=1
There may be 1 to 10 directory levels with some of the URLs. It's highly unlikely, but if this RewriteCond/Rule could be expandable, that'd be great.
However, the "edit", the "id", and file names may be different. I think that explaining this is very hard to achieve especially because of the hundreds of possibilities.
Basically, I'd like to be shown the file if it exists, and there is nothing else after the file name in the url. If it's a file and has more after the file name, assume it's a variable. If it's a directory with nothing else after it, I'd prefer if it could go to the directory index (index.php in this case). If it's a directory with a file name after it, I'd like to be shown that file.
Keep in mind that if a part of the URL is neither a directory or a file, assume it is part of the query, such as ?id=1
If necessary, I can put it in the server config, however, I'd like to keep it stupid simple.
I recognize this URL pattern from Zend Framework. How Zend Framework does it, is rewrite everything to an index.php, which bootstraps the application, and does the actual routing according to the routing configuration set in the application.
If this is only in the /admin/ subdirectory, you could create the following rewrite (based on Zend's default .htaccess):
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^admin/.*$ - [NC,L] # Do not rewrite if it is an actual file/link/directory
RewriteRule ^admin/.*$ /admin/router.php [NC,L] # Rewrite to the router.php
And in the router.php, you can use the $_SERVER['REQUEST_URI'] to parse the URL, set variables in the $_SERVER['QUERY_STRING'], and include the proper PHP for the given URL, for example.
For the RewriteCond usage, check: http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond
Let's start
Firstly, you'll need to put the following code in a file named .htaccess, in whichever directory you are dealing with:
RewriteEngine on
Now the mod_rewrite module has been turned on, and is ready to accept further instructions. The RewriteRule command is the root of the module, which tells mod_rewrite what to do. Here is its syntax:
RewriteRule Pattern Substitute (Optional Flags)
Here's an example:
RewriteRule /articles/([0-9]+) /articles.php?id=$1
This will replace http://www.yoursite.com/articles/1/ with
http://www.yoursite.com/articles.php?id=1.
You don't have to limit yourself to numbers either, you can use [a-z] or [A-Z] too!
Here are some flags you can use:
f: send a 403 forbidden error to the browser
NC: make the rule case-insensitive
g: send a 410 gone error to the browser
Not only can you rewrite URLs using rules, but you can also add conditions to these rules, so they won't be executed in every case:
RewriteCond Test Condition
Here's an example of what you can do with conditions:
RewriteCond %{HTTP_USER_AGENT} ^Opera.*
RewriteRule ^/$ /index_opera.php [L]
RewriteCond %{HTTP_USER_AGENT} ^Netscape.*
RewriteRule ^/$ /index_netscape.php [L]
RewriteRule ^/$ /index.php [L]
This will load a special page for Opera and Netscape, and load a default page for people not using Netscape. Here are some variables you can use in your conditions:
HTTP_USER_AGENT (browser)
HTTP_REFERER (referring page)
HTTP_HOST (domain name - yoursite.domain.com)
TIME, TIME_YEAR, TIME_DAY, TIME_HOUR, TIME_MIN, TIME_SEC
Get to work!
Now that I've (hopefully) wet your appetite, you can get working on some great uses of mod_rewrite. Here are some examples of what can be achieved:
/books/456/ » /index.php?mode=books&id=456
/books/456/buy » /index.php?mode=buy&id=456
/book_456.html » /index.php?book=456
... and Create beautiful url’s with mod_rewrite
The Apache rewrite engine is mainly used to turn dynamic url’s such as :
www.yoursite.com/product.php?id=123 into static and user friendly
url’s such as www.yoursite.com/product/123
RewriteEngine on
RewriteRule ^product/([^/.]+)/?$ product.php?id=$1 [L]
Another example, rewrite from:
www.yoursite.com/script.php?product=123 to
www.yoursite.com/cat/product/123/
RewriteRule cat/(.*)/(.*)/$ /script.php?$1=$2
You can use this code in your /admin/.htaccess:
RewriteEngine On
RewriteBase /admin/
RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]
RewriteRule ^([^/]+)/?$ $1/index.php [L]
RewriteRule ^(.+?)/([^/]+)/([^/]+)$ $1/$2.php?id=$3 [L]
Related
I would like to make the URLs of my Store URL-friendly.
Current URL Structure
https://my-domain.com/store/store.php?page=packages&id=1
Desired URL Structure
https://my-domain.com/store/packages/1
And also for direct access to the PHP files such as:
https://my-domain.com/store/profile.php to https://my-domain.com/store/profile
How would I need to go after this? I really appreciate any help you can provide.
Also might be note worthy that in the base directory a WordPress site is running with its own .htaccess file.
I already tried it with this
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^store/store/page/(.*)/id/(.*) /store/store.php?page=$1&id=$2
RewriteRule ^store/store/page/(.*)/id/(.*)/ /store/store.php?page=$1&id=$2
But that didn't work
This code will work.
RewriteEngine will remove .php from all PHP Files
RewriteRule will rewrite url like page/id
For Removing .php extension
RewriteEngine On
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]
For page/id
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)? store.php?page=$1&id=$2 [L]
</IfModule>
You can use this for the first part:
RewriteRule ^store/((?!store)[^/]+)/([^/]+)$ /store/store.php?page=$1&id=$2 [L]
Although nothing is wrong with anyone else's answers, the more modern way to do this (including WordPress, Symfony and Laravel) is to send non-existent URLs to a single router script. By doing this, you only have to mess with an htaccess file once to set things up, and never touch it again if you add more "sub-folders", you can do all of that in just PHP. This is also more portable which means you can bring it to other server platforms such as Nginx with little changes, and don't need to deal with RegEx.
The htaccess is fairly straightforward. Route all requests that start with /store/ and don't exist as a file (such as images, JS and CSS) or directory to a single new file called router.php in your /store/ folder. This is an internal redirect, which means it isn't a 301 or 302.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^store/ /store/router.php [L]
Then in your new router.php file you can parse $_SERVER['REQUEST_URI'] to determine the URL that was actually requested, and you can even rebuild the global $_GET variable:
// Parse the originally requested URL into parts
$requestUrlParts = parse_url($_SERVER['REQUEST_URI']);
// Parse the query string into parts, erase the old global _GET array
parse_str($requestUrlParts['query'], $_GET);
// Handle
switch($requestUrlParts['path']){
case '/store/store.php';
include '/store/store.php';
exit;
// Custom 404 logic here
default:
http_response_code(404);
echo 'The page you are looking for cannot be found';
exit;
}
I'd also recommend putting the htaccess rule into the site root's htaccess folder, above WordPress's. There's nothing wrong with creating multiple files, this just keeps things in a central place and makes it easier (IMHO) to debug.
So I was perusing stackoverflow looking for the answers to PHP seo friendly path parameters and came across a couple of examples but nothing exactly like I need. Im sure my biggest problem is not fulling understanding RewriteRule. Anyway here is what I need:
1) I need to remove the (.php) from all the pages
http://www.example.com/directory1/file1 <---- no .php
http://www.example.com/directory1/file2 <---- no .php
http://www.example.com/anotherDirectory/file1 <---- no .php
2) pages down some directory be able to grab query parameters in an SEO friendly form.
http://www.example.com/directory1/file2/param1/value1/param2/value2
Hopefully with a $_GET. Here is the directory structure:
/index.php
/directory1/
--file1.php?param1=$1¶m2=$2¶m3=$3
--file2.php
/anotherDirectory/
--file1.php
This is what I have (but does not work i.e doesn't get query params)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^([a-z-]+)$ index.php/directory1/file1.php?param=$1 [QSA,L]
Side note:
1) How do I handle optional params? Like in the case param1-3 might be optional or just param2-3 might be optional
2) Also do I need a different set of rules for each file?
i have a question about writing a rule in the htaccess file which is located in the root directory of drupal. We use the Drupal 7 version.
We want to write a rule for the url that when i go to the page "/newpage/1/name" it should target the "/oldpage?id=1&user=name". So the targetpage is a page which is created in drupal itself (a added content from a contenttype).
But i always get the same "Page not found"-Error. I can access the "/oldpage" by the way
I tried some rules about simply rewriteUrl without any parameters (to make a start). But it also didn't work for me. Here my try:
RewriteRule ^oldpage /newpage [L,R=301]
This line is below this part:
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]
So are there any special rules for writing rules in the htaccess file in drupal? (maybe especially in version 7) or what is wrong on my code?
Reading this site Guide ,I would try the following line
RewriteRule oldpage?id=(.*)&user=(.*)/$ /newpage/$1/$2
I have a site that I'm working on, but I'm annoyed that I have to work with ugly URLS. So, I have a URL of http://example.com/user.php?id=54 and another of http://example.com/foobar.php?name=Test.
How could I convert both of them to pretty URLS without adding it to .htaccess for every URL I want to make pretty?
example.com/user.php?id=54 => example.com/user/54
example.com/foobar.php?name=Test => example.com/foobar/Test
I have this in my .htaccess file:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^([^/]+)/?$ $1.php [L]
RewriteRule ^$1/$3/? /$1.php?$2=$3 [NC]
Thanks,
Lucy
My full .htaccess file:
# include classes on every page
php_value auto_prepend_file Resources/Classes.php
# add custom Directory Indexes
DirectoryIndex index.php Default.php Down.php
# begin routing to pretty URLs
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^/(?!Resources)([0-9a-zA-Z-]+)/([0-9]+) /$1.php?id=$2 [NC]
RewriteRule ^/(?!Resources)([0-9a-zA-Z-]+)/([a-zA-Z-]+) /$1.php?name=$2 [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
Try this
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^user/([0-9]+) /user.php?id=$1 [QSA,L]
RewriteRule ^foobar/([0-9a-zA-Z-]+) /foobar.php?name=$1 [QSA,L]
if you want global rule you can make
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+) /$1.php?parameter=$2 [NC]
or more specifically
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)/([0-9]+) /$1.php?id=$2 [NC]
RewriteRule ^([0-9a-zA-Z-]+)/([a-zA-Z-]+) /$1.php?name=$2 [NC]
when argument will be a string it will pas name parameter and when argument will be integer there will be id parameter passed.
I may delete this answer in the future as it might be specific to my setup.
I recently discovered, using Apache, that anything after the URL was populating the PATH_INFO environment variable. This means that given your example, example.com/user/54, if user was a script the server could process, anything after it would be populated into PATH_INFO; in this case it would look like /54. This is a great find because with proper structure, you could make your own router similar to Rails.
I would create some landing page (e.g., index) which is going to be your application router: example.com/index/<model>/<id>/. Inside index would be your routing code. I'll use Perl to demonstrate, since it's better than PHP :) Note that index could be called anything that Apache can process (e.g., router.php, index.pl, application.rb); though, removing the extension adds to the beauty of the URL.
index:
#!/usr/bin/perl
use 5.012;
# Retrieve what you're looking for; obviously not production-ready
my ($model,$id) = $ENV{PATH_INFO} =~ m{^/([^/]+?)/([^/]+)};
# route the request
given($model){
when('user'){ callUser($id); } # callUser defined elsewhere, perhaps another script
when('foobar'){ callFoobar($id); } # callFoobar defined elsewher, perhaps another script
default { makePageDefault(); }
}
http://example.com/index/user/1: passes 1 to callUser()
http://example.com/index/foobar/5: passes 5 to callFoodbar()
http://example.com/index/user: calls makePageDefault() because regex was not smart enough to handle anything without an ID
http://example.com/index/diffmodel/1: also calls makePageDefault(), since we don't handle diffmodel didn't exist
The script above is not production ready because it doesn't perform any sanitation and doesn't handle all the use cases you will need. My guess is you want something similar to Rails (e.g., example.com/movie/1/edit). While Apache is designed to handle the routing for you, there is some convenience in being able to manage this close to where your application code lives.
I have not implemented this method, so I'm curious to hear if this is something used and if there's any reason not to trust it.
I'm working on a website that has been built sloppily.
The website is filled with regular links that are translated into the corresponding .php pages by the .htaccess page.
This is it:
RewriteEngine on
RewriteRule ^koral/(.*)/$ page.php?name=$1
RewriteRule ^koral/(.*)$ page.php?name=$1
RewriteRule ^(.*).html/(.*)/(.*)/(.*)$ cat.php?cat=$1&page=$2&order=$3&dir=$4
RewriteRule ^(.*).html$ cat.php?cat=$1
RewriteRule ^(.*)/(.*).html$ product.php?cat=$1&product=$2
<IfModule mod_security.c>
SecFilterEngine Off
</IfModule>
First of all, I would love some help regarding whether or not this page has everything it should. I've never messed with it before.
Secondly and my main issue, if, for example, I would write the address www.thewebsite.com/foobar.html, it would be translated into www.thewebsite.com/cat.php?cat=foobar by the .htaccess page, and it would give a database error (and reveal information about the database).
I've put a check into cat.php which checks if the category exists, but I can't redirect the user to the 404 error page. There's a page called 404.shtml in the website, but redirecting the user to it causes the .htaccess to just change it again to cat.php?cat=404.
Is the way they used the .htaccess page normal? Should I change this system?
And how are users sent to error pages? From what I understood the server should be doing it on its own?
I would love some clarification... There is some much about this subject I don't understand.
Update:
This is my new .htaccess page
RewriteEngine on
RewriteRule ^error.php?err=(.*)$ Error$1.html
# Only apply this rule if we're not requesting a file...
RewriteCond %{REQUEST_FILENAME} !-f [NC]
# ...and if we're not requesting a directory.
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^koral/(.*)/$ page.php?name=$1
RewriteRule ^koral/(.*)$ page.php?name=$1
RewriteRule ^(.*).html/(.*)/(.*)/(.*)$ cat.php?cat=$1&page=$2&order=$3&dir=$4
RewriteRule ^(.*).html$ cat.php?cat=$1
RewriteRule ^(.*)/(.*).html$ product.php?cat=$1&product=$2
<IfModule mod_security.c>
SecFilterEngine Off
</IfModule>
Because the redirecting is in the code and the user cannot see it, I allowed myself to write the link in a non-clean way. I tried turning it into a clean URL but the following does not do anything:
RewriteRule ^error.php?err=(.*)$ Error$1.html
Can someone please help me understand why? I thought since error.php is a real page, I should put it before the conditional but it didn't work. BTW, I saw in an article about .htaccess that the page should start with Options +FollowSymLinks. It seems to me that everyone sort of has their own way of writing it. Is there a guide or something like that, which I can be sure is authentic and covers all the bases there is about .htaccess?
Thank you so much!!
Using rewrite rules to work around links to .html pages that don't exist is unusual in my experience, but it's really just a different take on "pretty" URLs, e.g. www.thewebsite.com/foobar/ gets routed to cat.php?cat=foobar on the backend.
Your 404 issue is different. You need to be able to display error pages.
One option here is to rewrite requests as long as they don't request an existing file. This is very common for serving up static content like images, CSS files, and the like. To do this, you can use the -d and -f options to RewriteCond, which apply when requesting a directory and file respectively:
RewriteEngine On
# Only apply this rule if we're not requesting a file...
RewriteCond %{REQUEST_FILENAME} !-f [NC]
# ...and if we're not requesting a directory.
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^([^.]+)\.html$ cat.php?cat=$1 [L,QSA]
Now, requests to 404.shtml should go through, because you're requesting an existing file on the filesystem.
Note that the RewriteConds only apply to the single RewriteRule that immediately follows. For additional RewriteRules, also include additional RewriteConds.
Your regex is wrong anywhere. Literal dot needs to be escaped using otherwise it will match any character. Also it is better to use L and QSA flags to end each rule properly.
RewriteEngine on
RewriteBase /
RewriteRule ^koral/([^/]+)/?$ page.php?name=$1 [L,QSA]
RewriteRule ^([^.]+)\.html/([^/]+)/([^/]+)/([^/]*)/?$ cat.php?cat=$1&page=$2&order=$3&dir=$4 [L,QSA]
RewriteRule ^([^.]+)\.html$ cat.php?cat=$1 [L,QSA]
RewriteRule ^([^/]+)/([^.]+)\.html$ product.php?cat=$1&product=$2 [L,QSA]