.htaccess rewrite rule for directory structure - php

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&param2=$2&param3=$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?

Related

.htaccess PHP Parameter Friendly URL

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.

Manage slugs with PHP and .htaccess (mod_rewrite)

Let's call my site:
www.example.com
and I have a PHP file like this:
www.example.com/product.php?id=50
I would like to access it by using
www.example.com/product/50
but ALSO, very important, I have several subdirectories like
www.example.com/subsite/product.php?id=50
www.example.com/subsubsite/product.php?id=50
That must become
www.example.com/subsite/product/50
www.example.com/subsubsite/product/50
How can I solve it at best with PHP and .htaccess using mod_rewrite?
I banged my head with other questions like this one but to no avail.
I can't seem to find a solution that works flawlessly, taking care of all imported files like CSS, JS and PHP classes.
Ok so this might not be the complete answer but should help you find your way.
You can use regex to match your desired path pattern. So for example your htaccess might look something like...
# Check if module is installed
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# Check query for matching pattern and pass id, but also append additional query strings
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\/]+\/)?product\/([0-9]+)$ /$1product.php?id=$2 [L,QSA]
# If not file or directory on server, send to 404.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.php [L]
</IfModule>
And what this does is...
1. Match the uri with a regex pattern
Regex: ^([^\/]+\/)?product\/([0-9]+)$
^ - Start of string.
([^\/]+\/)? - matches any directory (if exists) and stores it for reuse.
product\/([0-9]+) - Your desired path e.g. product/50 and stores the number "id" for reuse.
$ - End of string.
2. Pass captured directory and id to our file
Like so: /$1product.php?id=$2 [L,QSA]
$1 is our directory name including the trailing slash e.g. subsubsite/
$2 is our product id e.g. 50
[L,QSA] The QSA flag means we can access additional query string parameters e.g. /product/50?show=all&updated=1. More about flags can be found here http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa
3. 404 anything not matching
Like so:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.php [L]
!-f If request is not a file
!-d If request is not a directory
/404.php The file used for presenting a 404 error.
Getting the id...
With the above, you can get the ID within your product.php file like so:
$id = (int)$_GET[ 'id' ];

Drupal 7 - RewriteRule in htaccess file with parameters

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

Apache Mod_Rewrite Multiple Levels

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]

Mod_ReWrite regex unknown variables count?

i store uploaded files at /storage/ this way
public-adam-luki-uploads-123783.jpg
park-hanna-adel-propic-uploads-787689.jpg
the '-' count unknown because it slice the pic description
i want my users to be able to access it as
http://site.com/public/adam/luki/uploads/123783.jpg
http://site.com/park/hanna/adel/propic/uploads/787689.jpg
i think it is the same problem here
mod_rewrite with an unknown number of variables
but i can't do it because i'm new to mod_rewrite module
i hope you can help me guys with the right rewriterule
The question you link to doesn't actually do what you are trying to do (although the principle is the same) what they do is convert the url to GET variables.
If all you want to do is convert / to - then you can use a simple rewrite rule that will run in a loop:
ReWriteRule ^(.*)/(.*)$ $1-$2 [L]
There are of course a few caveats to that...
Firstly, even if you are trying to get to a real directory/file the rule will still switch out / and - and leave you with a 404. You can get around that by adding conditions; to stop it rewriting real files:
RewriteCond %{REQUEST_FILENAME} !-f
You would do better however to limit the matches to only images (jpgs):
RewriteCond %{REQUEST_FILENAME} !-f
ReWriteRule ^(.*)/(.*)\.jpg$ $1-$2.jpg [L]
Preferred Solution
ReWriteCond %{REQUEST_FILENAME} !-f
ReWriteRule ^images/(.*)/(.*)uploads[-/](\d+)\.jpg$ images/$1-$2uploads-$3.jpg [L]
RewriteCond %{REQUEST_FILENAME} !-f
ReWriteRule ^images/(.*)$ storage/$1 [L]
This solution requires you to use urls like:
http://site.com/images/park/hanna/adel/propic/uploads/787689.jpg
The pseudo directory images means you can be sure that the url is actually one that you want to redirect and it doesn't break other images/links on your site.
The above rules take a url (like the example above) and transforms it like so:
images/park/hanna/adel/propic/uploads/787689.jpg <--- Original
images/park-hanna/adel/propic/uploads-787689.jpg
images/park-hanna-adel/propic/uploads-787689.jpg
images/park-hanna-adel-propic/uploads-787689.jpg
images/park-hanna-adel-propic-uploads-787689.jpg
storage/park-hanna-adel-propic-uploads-787689.jpg <--- Final

Categories