htaccess rewriterule query to url - .htaccess

I am trying to make this:
http://www.testsite.com/bacon
be this
http://www.testsite.com/index.php?food=bacon
so the user types in/clicks on a link that is http://www.testsite.com/bacon but the server interprets it as http://www.testsite.com/index.php?food=bacon.
Some explanation to any solutions would be valuable too.

You can use this code in your .htaccess file to make a vanity URL for your task
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC]
RewriteCond %{REQUEST_FILENAME} >""
RewriteRule ^([^\.]+)$ index.php?food=$1
Explanation
Our first line turns on the rewrite engine.
The line above checks to see if the request is a file
This line turns adds the .php extension. So for example if you URL is /friends, the friends.php file would be called.(So this part is optional according to your use case)
The final two lines pick up the url when it is not a file name, for example, your-url.com/philipbrown and routes it to profile.php?user=philipbrown.
Visit this link for more information

Related

htaccess - the second url param is not visible

example.com/play/music to example.com/play.php?c=music
here is my code which works:
RewriteRule ^play\/music$ play.php?c=music [L]
now I have an extra url param (id as integer) added:
example.com/play/music/54
need to be - example.com/play.php?c=music&id=54
here is my beginning try:
RewriteRule ^play\/music/\d+/?$ play.php?c=music&id=$1 [L]
the page is there but problem is with id param - php doesn't see it
could someone help and explain ?
also, maybe is possible to join both rules (with and without id) in one ?
With your shown samples, please try following .htaccess rules file. Make sure to clear your browser cache before testing your URLs and make sure your .php files(eg: play.php etc) are residing along with .htaccess rules file.
RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/?$ $1.php?c=$2&id=$3 [QSA,L]

Mod_rewrite only working with certain folder names

Context
I'm using mod_rewrite to make my links better for SEO. I made the following rule for my page expanded_debate.php:
Options -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^poll/([0-9a-zA-Z_-]+)/([0-9]+) expanded_debate.php?poll_title=$1&pollid=$2 [NC,QSA,L]
When I input this format in the URL (poll/filename/10, for example) I get a 404 error:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.46 (Unix) OpenSSL/1.1.1h PHP/7.4.12 mod_perl/2.0.11 Perl/v5.32.0
However, when I change the first folder name to certain words, such as "debate" and "expanded_debate" (but not "expandedebate"), the file loads after page refresh. For example:
RewriteRule ^debate/([0-9a-zA-Z_-]+)/([0-9]+) expanded_debate.php?poll_title=$1&pollid=$2 [NC,QSA,L]
works fine.
I have an older .htaccess file, titled ".htaccess11", with the following info, in case it's of any use:
#forbids users from going to forbidden pages
IndexIgnore *
Options -Indexes
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/(?:\ Ballot169)?
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
#404 error directions
ErrorDocument 404 /404.php
Question
Any idea why only certain terms in the first folder position ("^debate" in example above) work when using mod_rewrite?
There are no "poll" folders in my project, if that's of any interest.
Let me know if there are any questions.
The line
RewriteCond %{REQUEST_FILENAME}\.php -f
Means "Take the requested URL, map it to a full local path in the normal way, append .php to the resulting path, and then process the following rewrite rule only if there is an existing regular file at the modified path".
For example, the URL "poll/filename/10" will be rewritten only if there is a file called "poll/filename/10.php" in the relevant location.
Since the value of the AcceptPathInfo directive is evidently set to On, this condition will also be met if there is an existing file called "poll.php" or "poll/filename.php". That is why the rewrite rule works when you change "poll" to "debate" or "expanded_debate" – there are existing files called "debate.php" and "expanded_debate.php".
In any case, it sounds like this behavior is not what was intended. Removing the -f condition should give the desired result. Or, to prevent the rewrite rule from making existing files inaccessible, you could replace it with:
RewriteCond %{REQUEST_FILENAME} !-f
The exclamation point negates the -f test: "continue only if this file does not exist"
If you are using the %{REQUEST_FILENAME} server variable (anywhere), you should be aware of how the AcceptPathInfo directive will affect this, and consider setting that directive explicitly in the same .htaccess file.
If Options +MultiViews is in effect, then %{REQUEST_FILENAME} will match existing files whether or not the extension is included in the request (GET /foo will match an existing file "foo.php", "foo.html", etc.). And GET /foo.php will match in any case. So, omit the string "\.php" from the original rule.
Other configuration may also have an effect, too. The important point is that, unlike %{REQUEST_URI}, %{REQUEST_FILENAME} invokes all the processing that Apache would otherwise do to translate a URL into a local path.
(source)
NB: although I don't think it was the intention here, you actually might want to test for the existence of a local file as part of this rule. You could use a RewriteCond to check whether the back-end data file for a given poll has been manually created, and return 404 by default if it has not. That would be a simple way to prevent users from making up their own poll URLs at will.

Tricky .htaccess mod_rewrite syntax problem

I got stuck, and even reading through tons of forum posts didn't help me.
The challenge:
I need URIs to be rewritten and queries to be maintained
Examples 1:
example.com/test/23/result/7
shall be redirected to a script under
example.com/test/
That works quite well with an .htaccess entry like this:
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^test/(.+)$ test/?s=$1
The URI is displayed unaltered. The called script is called, and the additional subdirectory definitions can be retrieved in PHP either through variable $_GET['s'] or $_SERVER['REQUEST_URI']. All is fine so far. The problem starts when adding a query string:
Example 2:
example.com/test/23/result/7?id=16
shall be redirected to the same script under
example.com/test/?id=16
Even when I add [QSA] to the rewrite rule, the URI is not parsed correctly. I tried several ways to initiate a redirect. All failed. The redirect either points to a non-existing address or the query string gets lost. Besides the initial URI subdirectory information, here I would need the query string to be evaluated in my script. Both pieces of data need to be transferred to it.
Does anyone have a solution?
Thanks a lot for sharing your expertise!
I would go with following htaccess Rules. This assumes that you have index.php file which is taking care of non-existing pages request in later your Rules.
RewriteEngine ON
##Rules for handling index.php url here.
RewriteCond %{THE_REQUEST} \s/([^/]*)/.*\?index\.php\s [NC]
RewriteRule ^ %1?%{QUERY_STRING} [NC,L]
##Rules for non-existing pages here.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
###Rest of your rules go here.....

Htaccess for redirecting a directory to a file with the same name

After doing a quick lookup on how to manage sites with multiple language support, I find site.com/language/page/ the neatest url layout. (as I don't have the funds for site.language)
I have used htaccess to redirect the base site from site.com to site.com/language/
by using: RedirectMatch ^/$ /language/ where 'language' is language.html
But since I have a directory called /language/ so that all other pages in the given language can be put inside it, the site just shows up as the index of the directory.
How can I accomplish that kind of layout, if I want the main index page to show up in the url as site.com/language/ ?
Current htaccess that worked fine until I added the directory:
## Rewrite Defaults
RewriteEngine On
## Remove file extension + force trailing slash
RewriteCond %{REQUEST_URI} (.*)/$
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule (.*)/$ $1.html [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule .* %{REQUEST_FILENAME}/ [R=301,L]
## Redirect to /en-gb
RedirectMatch ^/$ /en-gb/
With the root folder looking like:
/language
stuff.html
morestuff.html
language.html
...
I would really appreciate help as this is currently a nightmare situation. When I try compiling the htaccess with answers to similar questions, everyone has just parts of what I am looking to achieve and thus I break the layout with every modification...
Is it possible to change the back-end filenames and accomplish this layout using only htaccess for front-end url rewriting since the url bar is the only thing that matters?
If I understand correctly, you should be able to solve this by removing the line:
RewriteCond %{REQUEST_FILENAME} !-d
Let me know if that works.

How to avoid URL and directory match problem when editing .htaccess file?

I have the following lines in the .htaccess file in the site directory:
RewriteEngine On
RewriteRule ^([a-z]{1}[a-z0-9_-]{3,20})$ account.php?username=$1&%{QUERY_STRING}
If it receives URL for example :
http://localhost/samplesite/johnsmith
it will rewrite it to
http://localhost/samplesite/account.php?username=johnsmith
which is fine.
The problem occurs when there is a directory named johnsmith in the site directory. then the URL is rewritten to and displayed as
http://localhost/samplesite/johnsmith/?username=johnsmith
and that is a problem. I am trying to implement account pages functionality for every user but if a user wants to register a username like some directory in the root the functionality will break? I tried adding rewrite conditions to check if the requested URL stands for an existing directory or a file :
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
but I don't know how to proceed.
If someone knows a better way to do account pages functionality for users I would appreciate to give me a piece of advice on that.
Can anybody help me solve this case? Thank you!
Your RewriteCond will work if it is in the correct place. Your full .htaccess should look like:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# ---------------------------------------------------------------See info below--
RewriteRule ^([a-z]{1}[a-z0-9_-]{3,20})$ account.php?username=$1&%{QUERY_STRING}
Also, you don't need the %{QUERY_STRING}. Instead you should use the QSA flag to append the rest of the query string...
RewriteRule ^([a-z]{1}[a-z0-9_-]{3,20})$ account.php?username=$1 [L,QSA]

Resources