rewrite a folder so all files display under new rewrite rule - php

Is there a way that I can rewrite a folder so that all the files under that folder follow the same rule? For example:
if i have a folder with say 5 php files (a.php, b.php, c.php, d.php, index.php) in it and i use the following rule:
RewriteRule ^products/storage/?$ /content/products/storage/index.php [QSA,L]
is there a way that I can get all the files to show to be accessed like: site.com/products/apples/a.php, site.com/products/apples/b.php, etc. without having to write a rule for each one?
I tried the following but it didnt work.
RewriteRule ^products/storage/?$ /content/products/storage/ [QSA,L]
I also need it to NOT overwrite my other rules such as:
RewriteRule ^products/storage/?$ /content/products/storage/product-name1/ [QSA,L]
RewriteRule ^products/storage/?$ /content/products/storage/product-name2/ [QSA,L]
any ideas?

Your problem is the trailing $ on the end of the regex. This will only allow a match if the full URI matches products/storage (with optional trailing slash) exactly. Instead, try the following and note the absence of the trailing $ character:
RewriteRule ^products/storage/? /content/products/storage/ [QSA,L]
This will match anything that starts with products/storage (with optional trailing slash). Alternatively, if you wanted to capture and re-use everything in the URI that followed products/storage/ you could try:
RewriteRule ^products/storage(/?.+)?$ /content/products/storage$1 [QSA,L]
UPDATE
Should you need to preserve other RewriteRules as your updated question suggests, you should look to add a RewriteCond condition like so:
RewriteCond !^products/storage/?$
RewriteRule ^products/storage(/?.+)?$ /content/products/storage$1 [QSA,L]
The RewriteCond tells the RewriteRule to only process if the condition is not met.

Related

Rewrite subdomain and URL-path to URL parameters but allow access to files

I'm struggling with my .htaccess file and setting it up the way I want it. The main function is a website that gets the language from the subdomain and the current page from the subfolders.
Requirements
I have three requirements that I need my .htaccess file to do;
Wildcard subdomain redirected to lang variable
Subfolder(s) redirected to page variable
Local files respected (this is where I'm stuck)
(Bonus) Split up the page variable into segments for each slash; page, sub1, sub2, etc
Examples
en.example.com/hello -> /index.php?lang=en&page=hello
es.example.com/hola -> /index.php?lang=es&page=hola
(Bonus) en.example.com/hello/there/sir -> index.php?lang=en&page=hello&sub1=there&sub2=sir
My current .htaccess
This is my current setup which actually kinda works, if I don't need any local files (lol). This means local images aren't found when my .htaccess below is active. I tried adding RewriteCond %{REQUEST_FILENAME} !-f to respect local files but that breaks the whole file it seems - and I don't know why.
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{HTTP_HOST} ((?!www).+)\.example\.com [NC]
RewriteRule ^$ /index.php?lang=%1 [L]
RewriteCond %{HTTP_HOST} ((?!www).+)\.example\.com [NC]
RewriteRule ^(.+)$ /index.php?lang=%1&page=$1 [L]
RewriteRule ^index\.php$ - [L]
RewriteRule ^(.*)$ /index.php?page=$1 [L,QSA]
If your URLs don't contain dots then exclude dots from your regex - this naturally excludes real files (that contain a dot before the file extension). This avoids the need for a filesystem check.
Your script should handle /index.php?lang=%1 and /index.php?lang=%1&page= exactly the same, so the first rule is superfluous.
RewriteRule ^index\.php$ - [L]
This rule should be first, not embedded in the middle.
Try the following instead:
RewriteRule ^index\.php$ - [L]
RewriteCond %{HTTP_HOST} ^((?!www).+)\.example\.com [NC]
RewriteRule ^([^.]*)$ /index.php?lang=%1&page=$1 [QSA,L]
RewriteRule ^([^.]*)$ /index.php?page=$1 [QSA,L]
Your last rule that rewrites everything else to index.php, less the lang URL param is questionable. Why not just include this in the preceding rule and validate the language in your script? Which you need to do anyway.
Assuming there is always a subdomain, then your rules could then be reduced to:
RewriteRule ^index\.php$ - [L]
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
RewriteRule ^([^.]*)$ /index.php?lang=%1&page=$1 [QSA,L]
Requests for the www language are then validated by your script and defaulted accordingly, as if the lang param was not passed at all (which you need to be doing anyway).
If your subdomain is entirely optional and you are accessing the domain apex then make it optional (with a non-capturing group) in the regex:
RewriteCond %{HTTP_HOST} ^(?:(.+)\.)?example\.com [NC]
:
The lang param would then be empty if the domain apex was requested.
(Bonus) en.domain.com/hello/there/sir -> index.php?lang=en&page=hello&sub1=there&sub2=sir
It would be preferable (more efficient, flexible, etc) to do this in your PHP script, not .htaccess.
But in .htaccess you could do something like this (instead of the existing rule):
:
RewriteRule ^([^/.]*)(?:/([^/.]+))?(?:/([^/.]+))?(?:/([^/.]+))?(?:/([^/.]+))?$ /index.php?lang=%1&page=$1&sub1=$2&sub2=$3&sub3=$4&sub4=$5 [QSA,L]
The URL params are empty when that path segment is not present.
It is assumed the URL-path does not end in a slash (the above will not match if it does, so a 404 will result). If a trailing slash needs to be permitted then this should be implemented as a canonical redirect to remove the trailing slash. Or reverse the logic to enforce a trailing slash.
This particular example allows up to 4 additional "sub" path segments, eg. hello/1/2/3/4. You can extend this method to allow up to 8 (since there is a limit of 9 backreferences in the Apache syntax) if required. Any more and you will need to use PHP. (You could potentially handle more using .htaccess, but it will get very messy as you will need to employ additional conditions to capture subsequent path segments.)
I tried adding RewriteCond %{REQUEST_FILENAME} !-f to respect local files but that breaks the whole file it seems
That should also be sufficient (if dots are permitted in your URLs). But I wonder where you were putting it? It should not "break" anything - it simply prevents the rule from being processed if the request does map to a file - the rule is "ignored".
This is of course assuming you are correctly linking to your resources/static assets using root-relative (starting with a slash) or absolute (starting with scheme + hostname) URLs. If you are using relative URLs then they will probably result in 404s. If this is the case then see my answer to the following question on the Webmasters stack:
https://webmasters.stackexchange.com/questions/86450/htaccess-rewrite-url-leads-to-missing-css

.htaccess redirect urls with spaces

I am trying to redirect all invalid urls to my index.php file via my .htaccess file.
Unfortunately I keep getting an Apache error.
My .htaccess file
RewriteEngine on
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^([a-zA-Z0-9\-\_\/]*)$ index.php?p=$1
RewriteRule ^([A-Za-z0-9\s]+)$ index.php?p=$1 [L] 
This invalid url shoud redirect to index.php:
/vacatures/jobapplication/facility-manager%20qsdf
But it throws the object not found 404 Apache error.
The rule you have which allows spaces does not allow hyphens. The rule you have which allows hyphens does not allow spaces. So anything which includes both will not match either.
Your invalid URL facility-manager%20qsdf includes both.
My guess is that your RewriteCond is supposed to apply to both rules, but that is not what is happening now, it will apply only to the first RewriteRule after it. You can solve all these problems by including just 1 RewriteRule, and amending it to accept everything you want:
RewriteRule "^([A-Za-z0-9\-\_\/\s]+)$" index.php?p=$1 [L]
Note that this requires at least one of the characters in your character class, in other words it will not match your "home" location when there is no path ("http://somewhere.com/"). If you want to also match for that location, change the + to a *, to allow 0 or more character matches.
Your rewrite rules do not match the url you indicated. Your REQUEST_URI is
/vacatures/jobapplication/facility-manager%20qsdf
I suspect the URL decoding is not done before the RewriteRule matching and therefore it's trying to match literally %20, yet % sign is not included in your match. I'm not sure why you're using two RewriteRules - why not do something like this?
RewriteEngine on
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteCond %{REQUEST_URI} !^index.php(\?.*)?$
RewriteRule ^(.*)$ index.php?p=$1 [L]

Set .htaccess rules to specify different folders

I want to set a rule in .htaccess if I enter in the url www.mydomain.com/compare.php set 'public_html' as root otherwise anything come in the url set root as 'public' folder.
RewriteRule ^(?!compare-source.php).*)$ public/$1 [L]
I want to achieve following result.
if url is www.mydomain.com/compare.php hit following file.
public_html/compare.php
if urls are www.mydomain.com/ OR www.mydomain.com/home etc hit following file.
public_html/public/index.php
I am weak in regex and in these apache rules always :-( can someone give me the solution with good description?
Your answers are welcome, please can you describe how this crazy things work in detail. Thanks.
Try:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public
RewriteRule ^((?!compare\.php).*)$ /public/$1 [L]
The RewriteEngine directive enables or disables the runtime rewriting engine.
The RewriteCond directive defines a rule condition. The following Rule is only used if this condition is met; In our case, if REQUEST_URI (the path component of the requested URL) does not (because of !) begin (because of ^) with /public. We need this condition because we don't want to rewrite already rewritten URL - that would cause loop and Internal error 500.
Finally, the RewriteRule will match regex Pattern (^((?!compare\.php).*)$) against part of the URL after the hostname and port, and without the leading slash. If the pattern is matched, the Substitution (public/$1) will replace the original URL-path.
In plain language, if URL path does not begin with compare.php (because of ?!), pick everything (.*) between beginning (^) and end ($) and place it in variable $1. Then replace the original URL path with /public/$1.
#Anubhava's answer is also correct, he just placed both conditions in RewriteRule, and also it could be written even more readable as:
RewriteCond %{REQUEST_URI} !^/public
RewriteCond %{REQUEST_URI} !^/compare\.php
RewriteRule ^(.*)$ /public/$1 [L]
You can use this .htaccess in site root:
RewriteEngine On
# route /home/ or /home to /
RewriteRule ^home/?$ / [L,NC]
# if not compare-source.php or public/* then route to /public/*
RewriteRule ^(?!public/|compare-source\.php$).*)$ public/$1 [L,NC]

Using .htaccess to clean GET URL

Before anyone comments, I know there are a lot of posts created on this topic, but none of them seem to solve my problem, that is why I have started this thread.
So, I have a page in my website called project.php which is used in GET query like so: project.php?id=12 I want to have a .htaccess file that converts the given URL into localhost/MyWeb/project/id/12/. I've literally followed every single post regarding that topic but none of them seem to work.
Also, along with that, I want all my .php and .html files to be shown just with their names, i.e localhost/MyWeb/index.php/ becomes localhost/MyWeb/index/ and localhost/MyWeb/sub1/sub2.php becomes localhost/MyWeb/sub1/sub2/.
EDIT:
The reason why I did not add my work in first place was because I didn't think it would be any helpful. But here it is:
RewriteEngine On
RewriteRule ^([0-9]+)$ project.php?id=$1
RewriteRule ^([0-9]+)/$ project.php?page=$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^([^\.]+)$ $1.html [NC,L]
Firstly, you are operating out of a sub-directory (MyWeb), which means you need to set a RewriteBase. Also, you need to ensure that your .htaccess file is placed inside that sub-directory, and not in the localhost document root.
So, below RewriteEngine on, insert the folloeing line:
RewriteBase /MyWeb/
Next, you stated that you want to convert project.php?id={id} to project/id/{id}, but your code omits the /id/ segment. I also noticed that you have two rules, and that the second one contradicts your question, so I am only going to show you the change you need to make for the first rule, until such time as you clarify what the second rule is for.
To make the project URI work, change the very first rule to:
RewriteRule ^project/id/([0-9]+)/?$ project.php?id=$1 [QSA,L]
This will match the URI you want, with an optional trailing slash. I've also added the QSA flag which appends any extra query string parameters to the rewitten URI, as well as the L flag which stops processing if the rule is matched.
Next, to omit the .php or .html from your URIs, change the last three lines to the following:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [L]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]
When you make a request to localhost/MyWeb/index, Apache will check to see if localhost/MyWeb/index.php or localhost/MyWeb/index.html exist, and will then serve whichever one it finds first.
If you have both the PHP and HTML files, then the PHP one will be served, and not the HTML one. If you prefer to serve HTML files, then swap the two blocks around.
Unfortunately, I don't know of a good way to force a trailing slash for these, specifically because of the condition that checks for their existence. In other words, it won't work if you request sub2/, with the trailins slash because it would need to check if sub2/.php exists, which it does not.
Update: For added benefit, place these two blocks just below the new RewriteBase you set earlier to redirect the old URIs to the new ones whilst allowing the rewrites to the new URIs to still work:
RewriteCond %{THE_REQUEST} \/project\.php\?id=([0-9]+) [NC]
RewriteRule ^ project/id/%1/ [R=302,L,QSD]
RewriteCond %{THE_REQUEST} \/MyWeb/(.+)\.(php|html)
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ %1 [R=302,L]
For reference, here's the complete file: http://hastebin.com/gacapesoqe.rb

Apache rewrite rules doesn't work only with particular prefix

I've some problem with a script I'm writing.
I have those kind of URLs:
forum.php?f=topic&g=$1&id=$2&alias=$3
forum.php?f=group&g=$1
forum.php
I need to rewrite those for have:
/forum/group/id-alias_topic > forum.php?f=topic&g=[GROUP]&id=[ID]&alias=[ALIAS_TOPIC]
/forum/group > forum.php?f=group&g=[GROUP]
/forum > forum.php
I tried with:
RewriteRule ^forum/([\w'-]+)/([0-9]+)-([\w'-]+) forum.php?f=topic&g=$1&id=$2&alias=$3
RewriteRule ^forum/([\w'-]+) forum.php?f=group&g=$1
RewriteRule ^forum/ forum.php
But it doesn't work. It shows me only forum.php
Every URL starting with /forum shows me the default page provided by /forum.php
For example, forum.php will show the text "MAIN PAGE".
forum.php?f=topic&g=[GROUP]&id=[ID]&alias=[ALIAS_TOPIC] should show me "GROUP + ID + ALIAS_TOPIC"
But if I visit /forum/android/1-first_topic it shows me "MAIN PAGE"
If I replace ^forum with, for example ^foru, it works.
I've cleaned my browser cache and restarted apache, but it still doesn't work.
Also with other browsers the problem is the same.
In my /var/www there are those files and directories:
administrator.php assets cache forum_functions.php forum.php functions.php global.php index.php media notfound.php OLD pwdgen.php robots.txt rss.php simple_html_dom.php store.php template v.php
Do you have some advice?
Rewrite.log: http://pastebin.com/MeapYeBA
Because you have not used the [L] (last) flag and not anchored the end of the expressions with $ each one matches the last rule after dropping through the first two.
For example, this URL will match both the first and last rules: example.com/forum/group/123-thing because the last rule matches forum/ and anything that follows it if not terminated by $.
Add [L] flags to prevent fall-through, and terminate the regex with $
# Don't apply these if the file actually exists (like forum.php)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# This one doesn't really need to terminate in $
RewriteRule ^forum/([^/]+)/([0-9]+)-(.+) forum.php?f=topic&g=$1&id=$2&alias=$3 [L]
# This one must terminate with $
RewriteRule ^forum/([^/]+)$ forum.php?f=group&g=$1 [L]
# As must this one..
RewriteRule ^forum/?$ forum.php [L]
I have also replaced your [\w'-]+ with a simpler [^/]+ to match everything up to the next /. In the last rule, I added /? to allow for an optional trailing /. It will work just as well with [\w'-]+, but since you intend to match everything between /, [^/]+ is a more common pattern.
Each of the above rules is tested and working over at http://htaccess.madewithlove.be/
You Must put skip flag for stop other rules With tihs [S] at end of RewriteRule like
RewriteRule ^forum/([\w'-]+)/([0-9]+)-([\w'-]+)$ forum.php?f=topic&g=$1&id=$2&alias=$3 [S=2]
RewriteRule ^forum/([\w'-]+)$ forum.php?f=group&g=$1 [S=1]
RewriteRule ^forum/$ forum.php
Found a solution thanks to #Michael Berkowski
sudo nano /etc/apache2/sites-enabled/000-default
and remove all occurrences of MultiViews, then restart apache.

Categories