Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Here's my fix:RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.domain.com [NC]
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
RewriteBase /
RewriteRule ^postreview(\/?)$ /viewreview.php [QSA,NC,PT,L]
RewriteRule ^projectcars/index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^projectcars/(.*)$ /projectcars/index.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) template2.php [NC,L]
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
php_flag session.use_trans_sid off | I have 2 .htaccess files that I need to merge together. One is generated by wordpress and the other is the existing .htaccess file for the site. The 2 files are as follows:RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com$
RewriteRule ^(.*)$ http://www.mywebsite.com/$1 [R=301]
RewriteRule ^postreview/$ /viewreview.php [NC,PT,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ ./template2.php
<IfModule mod_security.c>
# Turn off mod_security filtering.
SecFilterEngine Off
# The below probably isn't needed,
# but better safe than sorry.
SecFilterScanPOST Off
</IfModule>
php_flag session.use_trans_sid off2nd file generated by wordpress:<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /projectcars/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /projectcars/index.php [L]
</IfModule>I've tried several ways to combine them, but I either get a redirect error or a internal server error. | Combine 2 .htaccess Files |
Use<link rel="canonical" href="FULL_PROPER_URL" />in your web pages. This will tell Search Engine to use that URL when displaying search results and will treat this a s main URL when seeing duplicate URLs. Details are here:http://www.google.com/support/webmasters/bin/answer.py?answer=139394http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.htmlUse 301 Permanent Redirect. Please note that this WILL NOT stop Google or any other search engine to requesting.phppages if such link is publicly available on some other site.This needs to be placed in .htaccess file in website root folder. If placed elsewhere some tweaking may be required.Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# redirect to .php-less link if requested directly
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+
RewriteRule ^(.+)\.php $1 [R=301,L]The above rule will do 301 redirect to a php-less URL. It will only redirect if .php file was requested directly and will not touch already rewritten URLs. | I've recently removed the.phpextension from all of my pages.Google results are still showing:www.mysite.com/page.php
www.mysite.com/directory/page-example.phpThese are now dead links. The new ones are:www.mysite.com/page
www.mysite.com/directory/page-exampleWhat would be the appropriate redirect so that if someone clicks one of the .php URLs, they are redirected to the extension-less URL | Redirecting all URLs that end in .php to no extension |
You will needmod_rewriteenabled for this. Start with placing these lines into .htaccess:RewriteEngine On
RewriteBase /TBH I'm not 100% sure what do you mean exactly by permalink and how do you want to redirect, so I will provide 2 variants for each URL: rewrite (internal redirect) and redirect (301 Permanent Redirect).1. This will rewrite (internal redirect) request forhttp://example.com/examptohttp://example.com/examp.phpwhile URL will remain unchanged in browser:RewriteRule ^examp$ examp.php [L]2. This will do the same as above but with proper redirect (301 Permanent Redirect) when URL will change in browser:RewriteRule ^examp$ http://example.com/examp.php [R=301,L]3. This will rewrite (internal redirect) request forhttp://example.com/examptohttp://example.com/user.php?u=exampwhile URL will remain unchanged in browser:RewriteRule ^examp$ user.php?u=examp [QSA,L]4. This will do the same as above but with proper redirect (301 Permanent Redirect) when URL will change in browser:RewriteRule ^examp$ http://example.com/user.php?u=examp [QSA,R=301,L]Useful link:http://httpd.apache.org/docs/current/rewrite/ | I want to redirect a link to another with .htaccess file in Linux host. Can you help me?from: http://example.com/examp
to: http://example.com/examp.phpAnd another one for my other sitefrom: http://example.com/examp
to: http://example.com/user.php?u=examp | How to create permalink in htaccess |
Maybe this will help:RewriteCond %{REQUEST_URI} !(.*).php$ [NC]
RewriteRule ^.* - [F,L]Several nice examples are here:Apache wiki: RewriteCond | I am using this code to send all the request to a single php file:RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) myfile.php?id=$1 [QSA,L]But now I want to also blockdirect accessto myfile.php and other phps. I don't want the php files to open directly via browser, but they must work for includes and such.How can I do this? | Blocking specific file extension with htaccess? |
You can use .htaccess for apache, create file in your root folder of web mainly "htdocs" name it ".htaccess" add next content to it<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
Options -Indexes
</IfModule>in your php file you can access data from $_GET$_GET['url'];Then you can use data to parse what you need. | I am working on building my first search-engine friendly CMS. I know that perhaps one of the biggest keys to having and SEO site is to have search-engine friendly URLs. So having a link like this:http://www.mysite.com/product/details/page1will result in much better rankings than one like this:http://www.mysite.com/index.php?pageID=37I know that to create URLs like the first one, I have one of two options:use a web technology, in this case PHP, to create a directory structureleverage Apache'smod_rewriteadd-on to have these URLs passed to a PHP processorAs far as the PHP goes, I'm pretty comfortable with anything. However, I think the first option would be more difficult to maintain.Could someone show me how to write an.htaccessfile, which will:silently direct SEO URLs to a processor scriptnot redirect if the requested URL is an actual directory on the serverIs there a better way than the way I am trying it? | Search-Engine Friendly URLs |
Keep all the images in their own directory, and in that directory, put a .htaccess file with this in itRewriteEngine On
RewriteCond %{HTTP_COOKIE} !^.*name-of-my-cookie.*$ [NC]
RewriteRule .* /whatever/page [NC,L] | I'm building a site in which users can upload photos, and they can mark them as private, so no one can see them.I know how to use an ACL-based system in php, but anyone will still be able to access the photos if they have the direct link to the image file.Eg: User 1 wants to share Photo A with User 2, so he grants him access. User 2 right clicks on the image, and copies its url, eg 'http://example.com/private123.jpeg', and sends it to User 3. Now user 3 can see the image he shouldn't be able to see.To sum up, I need a way to protect images based on user permissions, but still have them loading lightning fast (so running a php script each time an image is requested, is discarded).Is it possible with apache? I was thinking that maybe I could set up a cookie when the user logs in, and let apache check that somehow. I don't care if cookies can be faked, 99,99+% of the users won't know how to do that, and the photos don't need more security than that. | How to restrict access to certain kind of content, with apache or .htaccess? |
In.htaccesstry this:RewriteEngine on
#unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
#resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
#redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php /$1 [R=301,L] | I want to make all my URLs uniformly clean. Which means all my URLs have no extensions, nor trailing slash, and if a person does enter in a.phpor trailing slash, it would simply redirect the person to the clean URL.Example:example.com/blog/file.phpandexample.com/blog/file/would both redirect toexample.com/blog/file | How can I make all my urls extensionless, without trailing slash. And redirect the .php and trailing slash to none? |
Try thisAddType application/x-httpd-php .php .htm .htmlORAddHandler application/x-httpd-php .php .htm .htmlAnd remove other overriding handlers forapplication/x-httpd-phpafter above code. | I recently played with a.htaccessfile to make one server to parse PHP files. Yesterday I uploaded the same.htaccessfile and tried to test a PHP file. But something went wrong: visiting my page the browser offers to download the the html page rather then viewing the page!On the server the filenames end in.html.I added the following to my.htaccessfile:AddType application/x-httpd-php .htmlI tried to find the htaccess file, but once uploaded it just disappears from the root dir.
I tried to upload other scripts I've found browsing. I even tried to search for some problem on a hosting forum. Nothing helped.
Please help! | htaccess - parsing php into html |
Try:RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.html
RewriteRule ^(.*)$ /index.html [L,R=301]As you mentioned that this doesn't work, I'd try:RewriteEngine on
RewriteCond %{REQUEST_URI} !^/aaa.html
RewriteRule ^(.*)$ /aaa.html [L,R=301]index.html is a general default file name, so there might be rules that are on the server level, not in your .htaccess. That depends on the server setup, though. | I have removed the blog from my domain and put a simple index.html instead.
How do I redirect all the incoming traffic so that it does not show a 404 error, but redirects to the index?I tried this, but it loops...RewriteEngine on
RewriteRule ^(.*)$ /index.html [L,R=301] | htaccess redirect everything except index page |
Figured it outAuthName "Htaccess"
AuthUserFile /var/www/test/.htpasswd
AuthType Basic
Satisfy Any
<Limit GET POST>
Order Deny,Allow
Deny from all
Allow from 111.111.111.111
Require valid-user
</Limit> | Is there a way to require the use of htpasswd if the user is not in a certain IP range?EDIT:K I have this right nowOrder Deny,Allow
Deny from all
AuthName "Htacess"
AuthUserFile /var/www/Test/.htpasswd
AuthType Basic
Require valid-user
Allow from 111.111.111.111
Satisfy AnyBut its giving me a 500 error | HT Access IP restriction and htpasswd |
Here's something that's easy, and will work on any local filesystem on linux:Upload (or write) the file to a temporary filenameMove the file (using themv(move) command, either in FTP, or command line, etc, or therenamecommand in PHP) to overwrite the existing one.When you execute themvcommand, it basically deletes the old file pointer, and writes the new one. Since it's being done at the filesystem level, it's an atomic operation. So the client can't get an old file...APC recommendsdoing thisto prevent these very issues from cropping up...Also note that you could use rsync to do it as well (since it basically does this behind the scenes)... | I have to write script in PHP which will be dynamicly replace some files on server from time to time. Easy thing, but the problem is that I want to avoid situation when user request this file during replacing. Then he could get uncompleted file or even error.Best solution to me is block access to my site during replacing by e.g. setting .htaccess redirecting all requests to page with information about short break. But normally .htaccess file already exist, so there may be situation when server gets uncomplited .htaccess file.Is there any way to solve it?Edit:Thank you so much for all answers, guys. You are briliant.@ircmaxell Your idea sounds great for me. I read what dudes from PHP.net wrote and I don't know if I understand all correctly.So, tell me: If I do all steps you wrote and add apc.file_update_protection to my php.ini, there will be no way to get uncompleted file by user by any time? There will be always one, correct file? Are you sure at 100% ?It is very important to me coz these replacements will be very often and there is big chance to request file during renaming. | Best way to replace file on server |
Specify[QSA](Query string append) so you may pass a query string after your url.RewriteEngine On
RewriteRule ^book/([^/]*)\.html$ book.php?title=$1 [QSA,L]PS: Why are you using*here? Wouldn't+suit better? | I'm developing a website using PHP.
My .htaccess has this rewrite rule:RewriteEngine On
RewriteRule ^book/([^/]*)\.html$ book.php?title=$1 [L]So the URL that looked like: www.example.com/book.php?title=title-of-the-book
turns into www.example.com/book/title-of-the-book.htmlIn a specific case, from another page in the site, I want to link to pages like this:
www.example.com/book.php?title=title-of-the-book?myfield=1
that then turns into
www.example.com/book/title-of-the-book.html?myfield=1.htmlBeing ther, I cannot acces the GET variables using the usual PHP way$variable = $_GET['myfield']How do I solve this problem? | Access GET variables with PHP + .htaccess |
I think the best way to do this is to adopt the MVC style url manipulation with the URI and not the params.In your htaccess use like:<IfModule mod_rewrite.c>
RewriteEngine On
#Rewrite the URI if there is no file or folder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>Then in your PHP Script you want to develop a small class to read the URI and split it into segments such asclass URI
{
var $uri;
var $segments = array();
function __construct()
{
$this->uri = $_SERVER['REQUEST_URI'];
$this->segments = explode('/',$this->uri);
}
function getSegment($id,$default = false)
{
$id = (int)($id - 1); //if you type 1 then it needs to be 0 as arrays are zerobased
return isset($this->segments[$id]) ? $this->segments[$id] : $default;
}
}Use likehttp://mysite.com/posts/22/robert-pitt-shows-mvc-style-uri-access$Uri = new URI();
echo $Uri->getSegment(1); //Would return 'posts'
echo $Uri->getSegment(2); //Would return '22';
echo $Uri->getSegment(3); //Would return 'robert-pitt-shows-mvc-style-uri-access'
echo $Uri->getSegment(4); //Would return a boolean of false
echo $Uri->getSegment(5,'fallback if not set'); //Would return 'fallback if not set'Now in MVC There usually likehttp://site.com/controller/method/parambut in a non MVC Style application you can dohttp://site.com/action/sub-action/paramHope this helps you move forward with your application. | I'm running PHP on a shared Apache web server. I can edit the .htaccess file.I'm trying to simulate a file file structure that is not actually there. For example, I would like for the URL:www.Stackoverflow.com/jimwigglyto actually displaywww.StackOverflow.com/index.php?name=jimwigglyI got halfway there by editing my .htaccess file as per the instructions in this post:PHP: Serve pages without .php files in file structure:RewriteEngine on
RewriteRule ^jimwiggly$ index.php?name=jimwigglyThis works nicely insofar as the URL bar still displayswww.Stackoverflow.com/jimwigglyand the correct page loads, however, all of my relative links remain unchanged. I could go back in and insert<?php echo $_GET['name'];?>before each link, but it seems like there might be a better way than that. Additionally, I suspect my whole approach might be off, should I be going about this differently? | Simulate file structure with PHP |
WithRedirectyou define the base path (path prefix) that is to be redirected; every path beyond that is redirected while just replacing the base path with the new base path.If you want to stick withmod_alias, you can useRedirectMatchand omit the match:RedirectMatch 301 ^/ http://www.smartphonesoft.com/ | I am trying to do a 301 redirect of everything from an old subdomain to a new.I have a simple .htaccessRedirect 301 / http://www.smartphonesoft.com/However if I goto the old URL with a subdir, it tries to redirect to the new domain with a subdir and fails.iehttp://forum.smartphonesoft.com/reminder/goes tohttp://www.smartphonesoft.com/reminder/When I would like it to gotohttp://www.smartphonesoft.com/How can I have everything simply redirected to the new domain root? | 301 redirect everything to new root? |
I removed my original code from /etc/httpd/conf/httpd.conf and added this to my vhost.conf on this domain<Directory "/var/www/rockchurch.com/httpdocs">
AddOutputFilterByType DEFLATE html txt xml css js php
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
php_admin_value open_basedir none
php_admin_value safe_mode off
Options FollowSymLinks
</Directory>
<Directory "/var/www/rockchurch.com/httpdocs/tiny">
RemoveOutputFilter DEFLATE html txt xml css js php
</Directory>And works well. Apparently having it in /etc/httpd/conf/httpd.conf universally adds it to all domains, which is great, but can't be changed in specific directories elsewhere. | I am trying to figure out how to disable the DEFLATE module (gzipping) for a specific directory on my server. This is what I have in /etc/httpd/conf/httpd.confAddOutputFilterByType DEFLATE text/html text/plain text/xml text/css
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/htmlI can add something to my .htaccess file in the specific directory or even add a something to my /vhosts/domain.com/httpdocs/conf/vhosts.conf file. I can't seem to get it to work though. Any suggestions? | How to disable the DEFLATE module for a specific directory? |
Lots of ways to deal with it on your own code. If however you're already using Google Analytics and don't care to use javascript for the test, spare yourself a lot of trouble and look athttp://www.google.com/websiteoptimizer/index.htmlUpdate (Reconfine): Google website optimizer no longer exists, this has been replaced with "Google Analytics content experiments"https://developers.google.com/analytics/devguides/platform/experiments-overview | I want to create a way to test different layouts on a page to see which get more conversions.For example. If I have 2 versions of a page and I send 50% to page A and 50% to page B and see which one converts more sales.So I am thinking maybe use .htaccess to rewrite half to page A and the other half to page B.But how can I do that with .htaccess is there a way? do I need to use PHP instead to do this?Also if there is a better way to do this, or any cautions I should be aware of, please let me know. | How to setup split test? |
+100RewriteRule ^/?lib/.+$ - [L]
RewriteRule ^(.*) index.php | I am using Apache to rewrite my URLs into clean URLs.RewriteRule ^(.*) index.phpCurrently this rewrites directories too, which is what I want, since I want everything run through my router/index.php file.What I would like to do however, is have one folder that I can access directly. This is for lib files such as .js and .css files. I know how to do this with an Alias, but I can't use that in a .htaccess file, which I need to use.How can I not rewrite a specific folder, eg. called "lib"?EDIT:I did find the following example of how to fake an Alias in .htaccess, but I can't get it working:RewriteRule /old-folder /new-folder [PT] | Apache rewrite URL but don't rewrite certain folder |
You are probably using a different Apache version with a different regular expression engine. The Apache versions since 1.3 use POSIX ERE while the versions since 2.0 use PCRE. And only PCRE support the non-capturing group(?:expr).So try a pattern without them:RewriteRule ^category/([0-9]+)(/([^/]+)(/([^/]+))?)(/([^/]+)(/([^/]+))?)?/$ ./category.php?pid=$1&catname=$3&page=$5 [L] | My previous server working fine.. Today I changed new server and getting RewriteRule cannot compile regular expression on my htaccess.How to fix this line.RewriteRule ^category/([0-9]+)(?:/([^/]+)(?:/([^/]+))?)(?:/([^/]+)(?:/([^/]+))?)?/$ ./category.php?pid=$1&catname=$2&page=$3 [L]Let me know :) | RewriteRule cannot compile regular expression |
You have to exclude the file you are redirecting to as that is also matched by the pattern:RewriteCond %{REQUEST_URI} !/item-display\.php$
RewriteRule ^([A-Za-z0-9\.-]+)/?$ item-display.php?bibid=$1 [L] | I need a set of fresh eyes on this. I'm having a tough time spotting the problem.In folder X I have an .htaccess file with the following two lines in it:RewriteEngine on
RewriteRule ^([A-Za-z0-9\.-]+)/?$ item-display.php?bibid=$1 [NC,L]My interpretation is that anything in that directory will then be redirected to the item-display page. The problem is that on the item-display page, echoing out the value of bibid outputs 'display-item'. So somehow I'm redirecting from:http://localhost/test/cat/item/14056ato:http://localhost/test/cat/item/item-display.php?bibid=item-displayAny ideas?Cheers | URL Rewriting/Regex Debug |
The query string is not part of the URI path that is tested in theRewriteRuledirective. This can only be tested with aRewriteConddirective:RewriteCond %{QUERY_STRING} ^a=([0-9]+)$
RewriteRule ^a\.php$ /b/%1? [L,R]
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^a\.php$ /c/ [L,R]But if you want it the other way (requests of/b/123are redirected to/a.php?a=123):RewriteRule ^b/([0-9]+)$ a.php?a=$1 [L] | I am trying to get Apache to redirect/a.php?a=123to/b/123(where 123 could be any number between 1 and 9999) but can't seem to get it to work.This is what I have in htaccess:RewriteEngine on
RewriteRule ^a.php?a=([0-9]+) /b/$1 [L]
RewriteRule ^a.php$ /c/ [L]With this going to a.php?a=123 results in 404, but going to just a.php works as expected.
I tried escaping the ? (RewriteRule ^a.php\?a=([0-9]+) /b/$1 [L]) but it still doesn't work.What am I doing wrong please? | RewriteRule - a.php?a=123 to /b/123 |
Try this:RewriteEngine on
RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/(.*) $3?lang=$1 [L,QSA]And for thecurrent pathproblem, you have to know how relative URIs are resolved: Relative URIs are resolvedby the clientfrom a base URI that is the URI (not filesystem path!) of the current resource if not declared otherwise.So if a document has the URI/en/foo/barand the relative path./bazin it, theclientresolves this to/en/foo/baz(as obviously the client doesn’t know about the actual filesystem path).For having./bazresolved to/baz, you have to change the base URI which can be done with theHTML elementBASE. | I'm writing multilingual website. I have several files on server like:/index.php
/files.php
/funny.phpAnd would like to add language support by placing language code into URL like this:http://mywebsite/en/index.phpwould redirect to:http://mywebsite/index.php?lang=enAndhttp://mywebsite/en/files.phpwould redirect to:http://mywebsite/files.php?lang=enI would like to put more languages for example:http://mywebsite/ch-ZH/index.phpAnd I would like this to work only for files with php and php5 extension. Rest of files should be the same as they are.So for example when i will go to addresshttp://mywebsite/ch-ZH/index.phpI would like my PHP to recognize that current path ishttp://mywebsiteand NOThttp://mywebsite/ch-ZHIt's necessary for me because in my PHP code I relate on current path and would like them to work as they are working now.Could you please write how to prepare htaccess file on Apache to meet this criteria? | How to translate /en/file.php to file.php?lang=en in htaccess Apache |
Try these rules:Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# For LocalHost !.php
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !=127.0.0.1
RewriteCond %{REMOTE_ADDR} !=127.0.0.1
RewriteCond %{REMOTE_ADDR} !=::1
## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php[?\s] [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^page/([\w-]+)/?$ page.php?type=$1 [L,QSA,NC]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ $1.php [L] | I have the following problem when I try to create a user-friendly URL, it returns a 500 error.Doesn't workRewriteEngine On
RewriteRule ^page/(.+)$ /page.php?type=$1 [L]Works this one only if I change the script nameRewriteRule ^page/(.+)$ /change-page.php?type=$1 [L]Is there any way to keep page.php that redirects to page? Thank youHere the full .htaccess configurationOptions +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
# For LocalHost !.php
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !=127.0.0.1
RewriteCond %{REMOTE_ADDR} !=127.0.0.1
RewriteCond %{REMOTE_ADDR} !=::1
## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
RewriteRule ^page/(.+)$ /page.php?type=$1 [L] | How I can configure correctly Apache rewrite rule for GET request? |
You can use this :RewriteEngine on
#1) redirect "help.thecrypto.app/" to /knowledgebase.php
RewriteCond %{HTTP_HOST} ^help.thecrypto.app$ [NC]
RewriteRule ^knowledgebase\.php$ / [L,R]
#2) internally map knowledgebase.php to the root /
RewriteRule ^/?$ /knowledgebase.php [END]This will serve/knowledgebase.phpif you visit your site hompage/. | I checked many other similar questions but I can't come up with a .htaccess rule that would work properly.I have a server containing a Knowledgebase system (knowledgebase.php). I don't want to show thisknowledgebase.phpin the URL, ever.Examples what I want:https://help.thecrypto.appshould show same url (now it showshttps://help.thecrypto.app/knowledgebase.phpwhen you visit)https://help.thecrypto.app/knowledgebase.php?article=1should show URLhttps://help.thecrypto.app/?article=1How can I do this?I tried many options, including this:RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /knowledgebase.php?/$1 [L] | httaccess change mydomain.com/knowledgebase.php to mydomain.com |
I searched for< Directory /var/www/ >in /etc/apache2/apache2.conf file and changed the belowAllowOverride NonetoAllowOverride Allandrestarted the apache. It solved my issue. | I am using Lumen for the first time. I placed my lumen files in folder Test and kept the folder inside /var/www/html path in server. My PHP version is7.4.3I have the following routes:$router->get('/key', function() {
return str_random(32);
});
$router->get('/', function () use ($router) {
return $router->app->version();
});Below is my htaccess:<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>But whenever I try to accesshttp://xx.xxx.xxx.xxx/Test/public/keyit showsThe requested URL was not found on this server.But if I try to accesshttp://xx.xxx.xxx.xxx/Test/public/it returns meLumen (5.7.8) (Laravel Components 5.7.*)How can I make all other routes also to work? | Lumen Routes shows 404 except root route |
+100I'm not sure I understand your problem, but you can redirect domains with:RewriteEngine on
# not for exemple.com
RewriteCond %{HTTP_HOST} !example\.com$ [NC]
RewriteCond %{HTTP_HOST} (?:^|\.)([^.]+)\.(?:[^.]+)$
RewriteRule ^ http://example.com/products/%1%{REQUEST_URI} [NE,L]Point all your DNS on the main website, and just change the name of the main domain (example.com) in this .htaccess | Considerabc.comis my main website using nameserversns1.testnameserver.com&ns2.testnameserver.com.I would like to redirect multiple domains as below:def.com to abc.com/products/def
ghi.com to abc.com/products/ghi
jkl.com to abc.com/products/jkl
mno.com to abc.com/products/mnoI tried the below:i set the same testnameserver for def.com,ghi.com,jkl.com,mno.com.tried some combination inRewriteCondand.htaccessbut i couldn't solve it.Anyone guide me to move further.Thanks all.Note:I can't use domain forwarding / host all the domains because it's should be dynamic (like 3500+ domains to 3500+ products) | How to redirect multiple domains to woocommerce product page dynamically? |
This works for me:AuthName "Stage"
AuthType Basic
AuthUserFile /var/www/html/.htpasswd
SetEnvIf Request_URI ".*data_sheets.*\.pdf" noauth
SetEnvIf Request_URI "/api/.+" noauth
SetEnvIfNoCase Request_Method OPTIONS noauth
RewriteEngine On
RewriteCond %{THE_REQUEST} \s/api/
RewriteRule ^ - [E=noauth:1]
Order Deny,Allow
Deny from all
Require valid-user
Allow from env=noauth
Allow from env=rewritten
Satisfy Any
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ /index.html [L] | We have a drupal websitea.comthat is password protected. I want alla.com/api/...URIs not to be, though. So I've read aboutSetEnvIf:AuthName "Stage"
AuthType Basic
AuthUserFile ~/.htpasswd
SetEnvIf Request_URI ".*data_sheets.*\.pdf" noauth
SetEnvIf Request_URI "/api/.+" noauth
SetEnvIfNoCase Request_Method OPTIONS noauth
Order Deny,Allow
Deny from all
Require valid-user
Allow from env=noauth
Satisfy AnyThe/api/foobarURIs are still asking for a password though. Since it's a Drupal website, with the help of anubhava we figured it has to do with how the request is handled by index.php.How to deal with that?EditAddingRewriteCond %{REQUEST_URI} ^/api/ [NC]
RewriteRule ^ - [E=noauth]right afterRewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]didnt help | How to use SetEnvIf with Request_URI when it is rewritten to index.php? |
In most instances, a 301 redirect is the best way to implement redirects on a website. Using a meta refreshwon'tlet the reading entity (Google, a browser or otherwise) know that it's permanent and thus would have a negative impact in terms of SEO.A 301 redirect essentially means "Moved Permanently" as an HTTP status code and will be recognised for SEO purposes.Achieving this within an .htaccess file is the most efficient way of doing this as it's all done in one place and won't require the potential editing of all the individual files (50 in your case).Do this as a simple list inside an .htaccess file:RewriteEngine on
Redirect 301 /oldfolder/file1.html /newfolder/file1.html
Redirect 301 /oldfolder/file2.html /newfolder/file2.htmlOr, if all the files reside in one folder, you could use a ReWriteRule similar to below that's a lot quicker to test and implement:RewriteEngine on
RewriteRule ^oldfolder/(.*)$ /newfolder/$1 [R=301,NC,L]For reference:R=301 tells search engines that the redirection is permanentNC tells the engine not to care about the characters in the ruleL tells Apache it's the last rule and will avoid parsing/loops etc | I have over 50 html pages that I'm going to move to different folders in the same domain.How to properly make 301 redirects for each one?Some people said to place the redirect inmetahtml tags. Like this<meta http-equiv="refresh" content="0; url=http://example.com/" />Some other people are saying to make it inside the .htaccess file, I'm not sure what's the best way?My goal is to redirect the old URLs to the URLs without losing the page rank in Google. | How to properly make 301 redirect |
change permalink/%postname%/to/%postname%Right below the RewriteEngine On line, add:RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R]Moreinfo htaccess code | WordPress adds trailing slash to each url as per permalink settings./%postname%/So if you browsewww.mysite.com/about-usyou will be redirected towww.mysite.com/about-us/Is it possible to disable this redirect so that the page is served with and without the trailing slash. | WordPress Trailing Slash |
if you type the URL in the browser, the method is going to beGETinstead ofPOST. What you can do is usePostmanor other alternatives of your choice to test your REST API for other methods likePOST,PUT,DELETE, etc.More info about HTTP methodshereHope it helps! | I have written REST api in slim framework. When i call authenticate API from browser it troughs'Method not allowed. Must be one of: POST'. Below is my code, please correct me where i went wrong.Index.php<?php
require 'vendor/autoload.php';
require 'Authenticate.php';
$app = new \Slim\App;
$app->post('/api/authenticate', \Authenticate::class);
$app->run();.htaccessRewriteEngine On
RewriteRule ^ index.php [QSA,L]URLhttp://localhost/project/api/authenticate | Slim Framework Method not allowed. Must be one of: POST (405) |
supply an extra header in the request [using JavaScript] and then write some code in a .htaccess file to check if the header is presentYou could get Apache to check for this (secret) header and internally rewrite the request to aviewAsSource.php-type file that then reads theREQUEST_URI(or a passed query string parameter) and returns the file source instead. Similar to @LucasKrupinski suggestion, except you don't need to include anything in the PHP file itself.For example, in your root.htaccessfile:RewriteEngine On
# Block direct access to any file in the /tools directory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^tools/ - [F]
# Display PHP source...
RewriteCond %{HTTP:X-Action} ^display-source$
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule (.+\.php)$ tools/display-source.php?url=$1 [L]For all.phprequests this checks for theX-ActionHTTP request header having a value of "display-source" and that the requested file exists. If these conditions are met then the request is internally written to a/tools/display-source.phpscript, passing the URL in theurlparameter. You could instead check the$_SERVER['REQUEST_URI']superglobal, but note that this also includes any query string that is passed on the request.Then, indisplay-source.php, something like:<?php
$url = isset($_GET['url']) ? $_GET['url'] : null;
if (isset($url)) {
$file = $_SERVER['DOCUMENT_ROOT].'/'.$url;
// Validate $file....
// :
highlight_file($file);
} | I am using PHP with Apache and wonder if there is a way to indicate from the client side that the requested PHP file shouldn't be executed/parsed. By standard, I want all PHP files to be executed when requested, but I want a way to indicate from the client side that the file should not be executed.A nice solution would be to supply an extra header in the request using JavaScript and then write some code in a.htaccessfile to check if the header is present, and if it is tell apache to not execute the file and just serve it as text.Using GET parameters or something else would also be okay.Is this possible? If so, how? | Tell Apache whether or not to execute PHP on requests |
To match against bothwwwandnon-wwwhost in a single line, you can use the following regex pattern :^(www\.)?example\.com$This matcheswww.example.comorexample.com.To force ssl www, you can use this :RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule (.*) https://www.example.com/$1 [L,R,NE] | I am trying to understand the following syntax (see usage context below):RewriteCond %{SERVER_NAME} ^example\.com$I have the above (with real domain name in place of example) in my .htaccess file. I would like to force it to be www.example.com.The website has SSL and the following SSL Coding was added by the SSL Install process at GoDaddy. So I trying to work with both this coding, and changing to force to www with the SSL.# BEGIN GD-SSL
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_USER_AGENT} ^(.+)$
RewriteCond %{SERVER_NAME} ^example\.com$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Header add Strict-Transport-Security "max-age=300"
</IfModule>
# END GD-SSLI tried to add mod rewrite rules to force www and they are not working. I think the problem resides in the RewriteCond %{SERVER_NAME} ^example.com$
which is not resolving to the "www". I thought I might need to add the www. to this, however, I am not sure if this is correct.Would this be the solution to change the ssl to force WWW in the URL? Or do I need to do something else entirely?RewriteCond %{SERVER_NAME} ^www\.^example\.com$Any help would be greatly appreciated. Thank you.Becky | RewriteCond %{SERVER_NAME} syntax |
Create asitefolder inside yourhtmlone. Then, put yourroysite there. Then, I would do it this way:1 - apache2/sites-enabled/roy.my-domain.com.conf<VirtualHost roy.my-domain.com:80>
DocumentRoot /var/www/html/site
ServerName roy.my-domain.com
<Directory /var/www/html/site>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>2 - .htaccess<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|robots\.txt)
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>3 - If it's not development, it's never a good practice to use the$_SERVER['HTTP_HOST']superglobal. Can be changed from the client side. Just use the right url.After you're done all that, restart apache. In Ubuntu is:$ sudo service apache2 restart | It's my first time i'm uploading codeigniter project to production and i'm getting error 404 from Apache server.error :Not Found
The requested URL /index.php was not found on this server.
Apache/2.4.18 (Ubuntu) Server at roy.my-domain.com Port 80I've read every article for 2 days and didn't found a solution....So here are my settings :Checked for rewrite mod in Apache - got "Module rewrite already enabled"
My project is in/var/www/roy/so the url isroy.my-domain.com/royApache2.conf<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
AccessFileName .htaccess.htaccess<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /roy/
RewriteRule ^([a-z0-9_-]+)\.html$ index.php/page/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|asset|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>config.php$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/roy/';
$config['index_page'] = '';autoload.php (i'm using Twig)$autoload['libraries'] = array('database','session','twig');I added permissions to both logs and cache dirThe controllers structurename Login.php -
class Login extends CI_Controller | Error 404 on Apache server with codeigniter |
+50Even though there are a lot of HTTP status codes (which areofficially maintained by the IANA), not all webservers support all of these. As of Apache 2.4, the status codes 418 and 451 are not supported and silently converted to error 500 by Apache.The latest additions of supported status codes in Apache 2.4 are 414 and 501 and a crash prevention for 400 (fromApache 2.4 change log):core: Support custom ErrorDocuments for HTTP 501 and 414 status codes.
PR 57167 [Edward Lu ]core: Prevent a server crash in case of an invalid CONNECT request with
a custom error page for status code 400 that uses server side includes.
PR 58929 [Ruediger Pluem]See thelist of supported HTTP status codes(as of Apache 2.4.4).See an older bug (filed against 2.2) regardingremapping of custom status codes to 500 errors.See thisprevious question regarding a similar problem(but also with Apache 2.2). | For my web page, I have a.htaccessdocument which looks like this<Files .htaccess>
order allow,deny
deny from all
</Files>
ErrorDocument 404 /websites/404/index.phpNow as far as I understand it you can include furtherErrorDocumentby just adding another line. For example<Files .htaccess>
order allow,deny
deny from all
</Files>
ErrorDocument 404 /websites/404/index.php
ErrorDocument 503 /websites/maintenance/index.phpHowever, when I try to add a page forHTTP 451using the following line of codeErrorDocument 451 /websites/451/index.phpand I reload my page I get aServer error! Error 500. I later found out this was becauseXAMPPwas no longer picking up my folder with the.htaccessfile in and the error could only be resolved by removing theErrorDocumentforerror 451. What is causing this and how can I fix it?NoteI also found that this happens forerror 418: I'm a teapotas wellEditJust to include a little more information about the software I am using. I am usingXAMPP Control Panel v3.2.2Apache 2.4.17 - This is the version which comes with XAMPP | htaccess "breaks" upon including an argument for HTTP 451 |
For 2.4 it now looks something like this:<RequireAll>
Require all denied
Require ip 123.123.123.123
Require ip 123.123.123.123
Require ip 123.123.123.123
</RequireAll>EDIT:Require ip 123.123.123.123
Require ip 123.123.123.123A document describing information critical to existing Apache HTTP Server users.https://httpd.apache.org/docs/trunk/upgrading.html | My hosting provider recently updated the server to Apache 2.4 and the rules to control access to a specific folder via .htacces file doesn't work anymore with this code:Order Deny,Allow
Deny from All
Allow from 123.123.123.123
Allow from 123.123.123.123
Allow from 123.123.123.123After reading Apache 2.4 documentation I understand i should use something like this instead:<RequireAny>
Require ip 123.123.123.123
Require ip 123.123.123.123
Require ip 123.123.123.123
</RequireAny>but it doesn't work. Any one who can help me figuring this out? Thank you! | .htaccess allow/deny ip using require apache 2.4 |
Hope this helps just afterRewriteEngine OnRewriteCond %{QUERY_STRING} ^m=1$
RewriteRule ^(.*)$ /$1? [R=301,L] | I just moved my blog from Blogger to WordPress, and have a problem with the mobile URL.WordpPress have a function to setup URL structure, so the URL for desktop is OK, but there is an additional?m=1in mobile version Blogger URL.This is what I'm trying to do:redirecthttp://www.example.com/2016/05/artical.html?m=1tohttp://www.example.com/2016/05/artical.htmlI tried this but it didn't work:RewriteCond %{QUERY_STRING} ^(.*)(^|&)m=1(.*)$
RewriteRule ^(.*)$ /$1?%1%3 [R=301,L] | How to use .htaccess to remove '?m=1' in the end of url? |
As with so many web technology questions, there is a strict, theoretical answer and a "good enough for what you probably want" answer: The strict answer is: You cant, it doesn't work that way. Since the client can send whatever user agent string it wants to, you have no way of knowing what client is actually behind any given request.The "good enough" answer that will prevent the vast majority of users from seeing your site with the "wrong" user agent is documented here:http://www.htaccesstools.com/articles/detect-and-redirect-iphone/The relevant .htaccess block from the link, which redirects requests from iPhone user agents to an iPhone specific site is:RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} iPhone
RewriteCond %{REQUEST_URI} !^/my-iPhone-site/
RewriteRule .* /my-iPhone-site/ [R]Which you could modify in your case to redirect users with the wrong client:RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !^MySecretClient$
RewriteRule .* <URL of a tropical island paradise> [R]There is one other answer to whatmightbe your intention in doing this. If this is part of your application's security strategy, it is a bad idea! This is what's known as "security through obscurity" and is a well-established anti-pattern that should be avoided. Any but the most casual attacker of your software will quickly realize what's going on, figure out what client your application is meant to run on, and spoof it. | So I'm in the process of building my own web-application type project. However, I only want the website to be viewable through a web client of mine. I have set the web client's user agent setting to a custom name (MySecretClient) and am now attempting to only allow access from browsers with the user agent,MySecretClient. Everyone else gets redirected.Is there a better way to go about doing this? | Best way to restrict a website to a single browser (user agent)? |
Lets go over basic regexs, we'll use Regex101 for this. The.is any character and*is a quantifier of the previous character/grouping zero or more times. So your first regex,RewriteRule ^(.*)$ script1.php?username=$1 [L,QSA]says rewrite anything that starts with anything and ends with anything toscripts1.php. That isn't what you want.Demo:https://regex101.com/r/hK0xY3/1With regexs it is best to be as specific as possible.I would make your rule for users:RewriteRule ^(user\d+)$ script1.php?username=$1 [L,QSA]Demo:https://regex101.com/r/hK0xY3/4The+is another quantifier here meaning one or more, so you could change that to an*if a number ins't required.You said you wanted a regex that finds if there is a/in the path. I think it is best to tell the regex what to look at but that is possible:^.+?\/Demo:https://regex101.com/r/hK0xY3/3With this approach though any directory request will be redirected... | I would like to redirect urls that don't go into directories to one script (script1.php for example), and urls that have categories to another script (script2.php). Basically I would like to do something like this:http://www.test.com/user1->http://www.test.com/script1.php?username=user1where script1.php gets the username and presents an appropriate page for that user. I have that part working with this code:RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ script1.php?username=$1 [L,QSA]The problem now is that I would also like to have descriptive product urls so that for examplehttp://www.test.com/clothes/jackets/cool-red-jacket-25redirects tohttp://www.test.com/items.php?category=clothes&subcategory=jackets&id=25. I have some code that should work for that too:RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([a-zA-Z-]+)/([a-zA-Z-]+)/.*-A([0-9-.]+)\.php$
script2.php?category=$1&subcategory=$2&id=$3 [L]The problem I'm having is combining these 2 types of redirection. The first redirect always redirects to its own page and the second redirect will never get reached. Is it possible to combine these 2 and in which way? Basically I need something like this for htaccess if possibleif(!urlHasDirectories) {
redirect to script1.php?username=$username;
} else {
redirect to script2.php?category=$category&subcategory=subcategory&id=$id;
} | Handle .htaccess redirects with different parameters? |
your hosting should support wildcard subdomain featureshttps://www.namecheap.com/support/knowledgebase/article.aspx/9191/29/how-to-create-wildcard-subdomain-in-cpanel | I am working on laravel and need to create subdomain using laravel dynamically without going cPanel or server setting.Say here I have abc.xyz.com and I want create {subdomain}.abc.xyz.com . where subdomain will dynamic.To access I have Use following code in laravel route.Route::group(['domain' => 'abc.xyz'], function()
{
return 'Main page will be loaded';
});
Route::group(['domain' => '{subdomain}.abc.xyz'], function()
{
return 'Subdomain page will be loaded';
});Also I have searched, but just found only way by .htaccess .Is it the only way to do this or is there any other ways also to create subdomain dynamically. | How to create subdomain dynamically without going cPanel |
If you are using Apache 2.4, you can do something like this<If "%{QUERY_STRING} =~ /q=.*?/">
Header set Foo "bar"
</If>https://httpd.apache.org/docs/2.4/mod/core.html#ifhttps://httpd.apache.org/docs/2.4/expr.html#examples | I am runing apache and I am trying to set a header Foo=bar only when the request has a variable "q" on the query string. I would like something like this in my htaccess:<RequestUri "q=">
Header set Foor "bar"
</RequestUri>Of course it does not work. I already tried using "Location" and "LocationMatch" but those are not allowed inside the htaccess. So how can I do that? | Header set with query_string |
The standard escape character for .htaccess regular expressions is the slash ("\").RewriteRule ^([a-z0-9/-]+)-c-([0-9_]+)\.html$ index.php [NC,L,QSA]
^^
RewriteRule ^([a-z0-9/-]+)-m-([0-9]+)\.html$ index.php [NC,L,QSA]
^^The slash will prevent the meaning of the dot and escape it so that the dot is taken verbatim as a character to match (period, ASCII code 46 / x2E) .The other suggestion given in the comment to create a character class consisting of the dot only ("[.]") does the job as well, but it's perhaps a bit over the top to create a character class while you only want to name a single character. But it's technically working (and has been suggested for example inescaping dot in Apache mod_rewrite).BTW:Apache rewrite uses Perl Compatible Regular Expression (PCRE)which is the same flavour of regex like PHP is using in thepreg_*family of functions which is PHP's preferred regex dialect. | I have a.htaccessfile that is used by an advanced SEO URL php system installed on my osCommerce site.It has the following rules that work just fine for most cases, but removing periods from my GET parameters:RewriteRule ^([a-z0-9/-]+)-c-([0-9_]+).html$ index.php [NC,L,QSA]
RewriteRule ^([a-z0-9/-]+)-m-([0-9]+).html$ index.php [NC,L,QSA]So URL like this:http://example.com//index.php?cPath=44_95&page=1&range=1.99_2.99gets rewritten according to the rule and the1.99_2.99becomes199_299.How can I escape the period safely? (ie. without causing some random side effects) | Safely escape period/dot (.) character in .htaccess mod_rewrite regex |
Removehttp://from 404 handler and have it like this:ErrorDocument 404 /404.phpThe URL that is causing 404 is available to you in404.phpusing:$_SERVER["REQUEST_URI"]Whenhttp://ise used in 404 handler server performs full redirection and you loose originalREQUEST_URI. | I've used the code below to create a custom 404 message (page not found) using a .htaccess file.RewriteEngine On
ErrorDocument 404 https://%{HTTP_HOST}/404.phpIt works well, but I want to know what was the wrong URL that caused this redirection. In other words, I need to fetchHTTP refererwhile user is in 404.php. So I have used$_SERVER['HTTP_REFERER']in 404.php, but it does not return anything.Where did I have mistakes? And what is your solutions to solve this problem? | How to find referrer URL while using htaccess 404 redirect? |
You can add this in the<head>section of your page's HTML:<base href="/" />so that everyrelative URLis resolved from that base URL and not from the current page's URL. | I have a personalized 404 error page in my web, withErrorDocument 404 404.htmin my.htaccess.The problem is, if you typewww.mydomain.com/whatever/whatever2.html, it shows the 404 page correctly, but the links are all broken, for example a link tohref="property.php"points towww.mydomain.com/whatever/property.php, that is a 404 error too.How can I fix this without changing all the routes to absolute routes? | Relative links on a custom 404 page |
Trysudo a2enmod rewriteandCheck your etc/httpd/conf/httpd.conf file.
It should have the following in it:AllowOverride Nonechange it toAllowOverride All | Hi i have installed the laravel on ec2 instance using this videowww.youtube.com/watch?v=8ARpTKWc6lQI have changed the document root path from/var/wwwto/var/www/html/laravel/publicin the deafult.conf file as described at the end of the videoBut now my when i open my website my homepagehttp://52.26.133.246/which have('/')shows fine but when i open my other page with routes like('AdminApp')or you can simple click on admin link on the navbar of home page with whole link ishttp://52.26.133.246/AdminAppit says404 page not foundand alsoThe requested URL /AdminApp was not found on this server.but when i use /index.php in the url the page is shown
here is the linkhttp://52.26.133.246/index.php/AdminAppAlso kindly check this link also to withoutindex.phphttp://52.26.133.246/welcomewith index.phphttp://52.26.133.246/index.php/welcomeKindly help me.
Thanks | laravel 5.1 says for all the other routes that except ('/') that 404 page not found on online Amazon Server using ec2 |
Adding the[PT]flag fixed it:RewriteEngine On
RewriteRule /whatever /cgi-bin/script.cgi [NC,PT]Now if somebody could just explain why that's needed and what is actually going on, I would be extremely grateful. | I'm trying to rewrite the URLhttp://domain.com/whateverTo:http://domain.com/cgi-bin/script.cgiMy .htaccess file looks like this:RewriteEngine On
RewriteRule /whatever /cgi-bin/script.cgi [NC]This doesn't work and gives me a 404 error. However, this works:RewriteEngine On
RewriteRule /whatever http://domain.com/cgi-bin/script.cgi [NC]But in that case, the URL change is vivible to the user. What am I doing wrong? | mod_rewrite: Rewrite URL to point to cgi script, but keep rewrite hidden |
You links are all relative links."images/icon.png"instead of"/images/icon.png". Because your url changed its URL base from:/viewRestuarant.php
Base: /to/raipur/something/1234
Base: /raipur/something/When the browser sees a link like:images/icon.pngit needs to prepend a base URL to it in order to know where the resource is located. By default it uses the host and base based off of the URL that it sees in the location bar. Since that's obviously not where any of these resources are, you need to either make your links into absolute URL's like:/images/icon.pngorhttp://example.com/images/icon.pngor add an explicit relative URL base into the header of your pages (between the<head> </head>tags):<base href="/" /> | I am a newbie for rewriting url, I have rewritten my url, but it is causing problem for all the relative paths used in the page like<link href="style/style.css" rel="stylesheet">
<link href="images/icon.png" type="images/ico" rel="icon" />
<img src="images/test.png" id="test">Even i have applied the following rewrite rule for them, but still i find 404 error in firebug console (first one is working but second is not working for relatvie)RewriteEngine On
RewriteRule ^raipur/([A-Za-z0-9-]+)/([0-9]+)$ /viewRestaurant.php?raipur=$1&id=$2
RewriteRule ^raipur/([A-Za-z0-9-]+)/([A-za-z]+)/ /$2/my console screenshotI had even debugged my rewrite rule intohtaccess testerand its working there as required | url rewriting is not working for relative paths |
+100Use this in yourpublic_html/.htaccessfileRewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^page/([0-9])/?$ /index.php?page=$1 [QSA,NC,L]RewriteCondchecks if the requested filename or directory already exist,RewriteRulewill be skipped. | How can I change a url of the following formatexample.com/page/1Toexample.com/index.php?page=1?When I enterexample.com/page/1it should redirect toexample.com/index.php?page=1What changes do I need to do in my .htaccess file?folder structure is as follows-Public_html
.htaccess
index.phpThanks. | Creating SEF urls using .htaccess |
You were close. Just modify your rules toRewriteCond %{HTTP_HOST} ^localhost$ [NC]
RewriteRule ^joomla(/.*)?$ - [END]The-says we do no processing on this URL. The[End]flag prevents all the rules below from firing. | I have an instalation on my htdocs folder that needs rewriterules to be processed like this:RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteCond %{REQUEST_URI} !^/admin?
RewriteCond %{REQUEST_URI} !^/payment?
RewriteRule ^(.*)$ %1/$1 [QSA]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^admin/(.*)?$ BACKEND-PHP/$1?domain=%1 [QSA]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^payment/(.*)?$ PAYPAL-API/$1?domain=%1 [QSA]But now, to test joomla i need add some rule in the htaccess file that stop processing rules if the given directory is "localhost/joomla" in order to joomla work properly.in pseudocode will be like this:RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
**RewriteCond %{HTTP_HOST} ^(localhost)$
**RewriteRule ^/joomla$ [END]
# (if the requested file is at joomla directory
# htaccess will stop processing)
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteCond %{REQUEST_URI} !^/admin?
RewriteCond %{REQUEST_URI} !^/payment?
RewriteRule ^(.*)$ %1/$1 [QSA]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^admin/(.*)?$ BACKEND-PHP/$1?domain=%1 [QSA]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^payment/(.*)?$ PAYPAL-API/$1?domain=%1 [QSA] | htaccess stop processing if given directory |
You can useServerTokensonly in the server config (httpd.conf):http://httpd.apache.org/docs/current/en/mod/core.html#servertokensIt's ok in.htaccessforServerSignature | I've added the following code to my .htaccess file in my website's root folder:# Disable server signature
ServerTokens ProductOnly
ServerSignature Off
# END SCCCIt causes my website to crash:Internal Server Error:
The server encountered an internal error or misconfiguration and was
unable to complete your request.Removing theservertokensline, it works as expected and removes the signature.How should I be disabling servertokens? Do I even need to if I'm disabling the signature? | Disabling servertokens via .htaccess breaks website |
Just place .htaccess file in the root folder with data below:<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</IfModule> | I recently created a website with laravel 4. I used XAMP to test my website on localhost and to make it easier I created a virtual host in the vhosts file which points to the public folder of my Laravel app. The website is working perfectly.Now I rented a webspace at One.com hoster. I opened the webspace with ftp and when I came on the "root" but there weren't any folders so I guess that the root location is the public location? I don't for sure.The normal structure of a Laravel app is like this:--> app
--> bootstrap
--> public
--> vendor
--> other filesThis doesn't work because I think that One.com doesn't use a public html folder. I tried to make it work but unfortunately. I moved the contents of the public folder to the root of my domain and moved all the other folders in a folder named core. Then I changed some config files index.php and paths.php but still it doesn't work.The question is what do I need to change to my folder structure to let it work on this One.com webserver and which files I need to adapt (.htaccess, paths.php)? I would like to protect my private folders of course.Thanks in advance. | How to configure laravel to use on hoster One.com |
Slim recommends using these rules for Apache. (.htaccess)RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]Rembember you have to set theAllowOverridedirective to "All" in the Apache config and make sure that "/public" is your root virtual directory. | I've built a Slim PHP app and published it on my webserver.The routes are only available if I browse directly via the index.php pagefor exampleexample.com/index.php/loginand/index.php/signupboth render the expected viewshowever if I omit index.php and browse to `example.com/login' or 'example.com/signup' I get a 404My.htaccessfile is located in the same directory asindex.phppublic/
├── .htaccess
├── index.phpthepublicfolder is configured as theDocumentRoot /var/www/example.com/publicin apacheMy.htaccessfile contains the following:<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>Any suggestions how to fix my routing? | Slim PHP routes not working |
You can use this rule:RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(image-provider)/(.+)$ $1?url=$2 [L,QSA,NC]Couple of issues in your rule:Leading slash is not matched in.htaccessYou must use.+to avoid matching/image-provider/as an URI. | I'd like the following image URLhttp://www.example.com/image-provider/article/1275449_inline3_scale_700xauto.jpgto be redirected to the following PHP script that will actually generate the contenthttp://www.example.com/image-provider?url=article/1275449_inline3_scale_700xauto.jpgI've tried the following syntax in my .htaccessRewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/image-provider/(.*)$ image-provider?url=$1 [L]With no success so far:I still get a 404. Is there something wrong in my .htaccess ? | htaccess : redirect an image path to a PHP script |
You can use this rule in your root .htaccess:RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(one)/?$ /$1.php [L,NC] | I have a website
eg :www.abcd.comin that there are many pages.
eg :www.abcd.com/one.php,www.abcd.com/two.phpI just want to remove the .php fromwww.abcd.com/one.phpand not from all the other pages.I have tried this part in .htaccess file.RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php | How to remove .php or .html extension from single page? |
I see that it's about fastcgi problem, i changed it to apache module from plesk control panel - PHP support (Run PHP as apache module)Now it's working | I transfered my website to a new dedicated server which is CENTOS and PHP Version 5.3.3 with PLESK.My problem is this, I'm getting "No input file specied" error in everypage expect homepage. Firstly i think it's a chmod problem than i set it to 755 to all folders and files in httpdocsSecondly googled and find a solution about .htaccessMy .htaccess is:SetOutputFilter DEFLATE
AddDefaultCharset UTF-8
DefaultLanguage tr-TR
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]And i changedRewriteRule ^(.*)$ index.php?/$1 [L]By this changes site started to work in a different way. There wasn't any error but in everypage i am redirecting to homepage.Hovewer when i write index.php into the url as guncebektas.com/index.php/yaptiklarimI can reach the page that i wantThan, I changed php.ini,cgi.fix_pathinfo=0nothing changed than Finally i decided to write here, thanks for your help.Site : guncebektas.com/
A page : guncebektas.com/yaptiklarim
I can reach : guncebektas.com/index.php/yaptiklarim | No input file specified plesk server4you |
Turns out my problem was somewhat unrelated. I had to rename my default controller php file to lowercase and the controller class name to lowercase and everything started to work. When CI looks for the default controller file, it searches in lowercase for the file; if I name my controller file "Home.php" instead of "home.php," CI misses it on Linux (since Linux file systems are case sensitive). | I have a default controller set:$route['default_controller'] = "Home";However, when I go tohttp://mydomain.com/, it says 404 Page Not Found, but when going tohttp://mydomain.com/Home, the controller loads fine. What could be the problem? I've been wracking my head for hours. My htaccess isposted hereif needed. Thanks! | CodeIgniter - Default controller not loading automatically |
Many different ways depending on how github accesses this, you'd add some stuff to the htaccess file in your document root (or where your readme file is).Using mod_authz:<Files "readme.md">
Order Deny,Allow
Deny from all
</Files>This will return a 403 forbidden forall requeststo/readme.md. If you want to whitelist a specific IP, You can add this right above theDeny from allline:Allow from 12.34.56.78which will whitelist requests sent from the 12.34.56.78 IP.Using mod_rewrite (which gives you a couple of options)RewriteEngine On
RewriteRule ^readme\.md$ - [L,F]This does the same thing. To whitelist an IP, add this before theRewriteRuleline:RewriteCond %{REMOTE_ADDR} !^12\.34\.56\.78$You can also return a 404 instead of a 403 Forbidden by replacing theFin the rewrite flags toR=404. If you need to whitelist a referer, you can add a condition (right above the rewriterule line) like this:RewriteCond %{HTTP_REFERER} !^https?://github\.com/ [NC]which will allow people to access the readme.md file if the link was embedded on a page fromgithub.com. | I have a plain text readme file that is in the root directory of my website which is version controlled with Git. I like to have the readme there because GitHub will display it when viewing that repo.However, when I go tomysite.com/readme.md, I get the readme file back. I do not want this file to be accessible to the public.What is the best way to effectively disallow the public from accessing this readme file without moving the file away from the root of the project? | How to keep readme from being web accessible |
Change the .htaccess ldap authentication code to,RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,NC,L]So the entire htaccess will look like below,#Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
#Basic ldap authentication goes here ...
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,NC,L] | I have a site made using Yii framework. I have used HTTP authentication (basic) for user login purpose. It is working fine. And after authentication it redirects to user profile but in url afterwwwparthttpsis appended.eg.https://wwwhttps.example.com/directory/I have also tried removing https part using .htaccess but no luck. Here is my .htaccess configuration:#Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
#Basic ldap authentication goes here ...
RewriteCond %{HTTP_HOST} ^wwwhttps\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,NC,L]and the login controller code:public function actionLogin()
{
$this->layout='//layouts/login_layout';
if(isset($_SERVER['REMOTE_USER']) && $_SERVER['REMOTE_USER']!='')
{
$username = $_SERVER['REMOTE_USER'];
$user = User::model()->findByAttributes(array('username'=>$username));
$ui = UserIdentity::impersonate($user->id);
if($ui)
Yii::app()->user->login($ui, 0);
$this->redirect(yii::app()->getBaseUrl(true).'/user/profile');
}
}Is it because of basic authentication or anything else? If I don't use basic authentication it works fine.... Please help me.
Thanks in advance!!! | after basic authentication redirect url modified |
First you should really understand what those rules are doing and what you really want to achieve. Then you can try to change the system to fit your needs.IfModuleensures everything inside is processed only whenmod_rewriteApache module is present. All the other directives are from this module.RewriteEngine Onenables URL rewriting.RewriteBase /tells the engine that the rules operate inside root. See also the general question onhowRewriteBaseworks.RewriteRule ^index\.php$ - [L]means that no more rules should be processed ([L]) if the current URL to be rewritten isindex.php. No rewrite takes place.RewriteRuledirective accepts aregex. See alsoregextag here on SO.AllRewriteConddirectives apply to the followingRewriteRule. Unless[OR]flag is added, they must be all satisfied at the same time to execute the rule. In this case they mean:Requested resource is not a regular file.Requested resource is not a directory.Rewrite any (at least one character long) URL toindex.php. This is the last ([L]) rule to be processed.When adding newRewriteRules, you probably want to use the WordPress way of doing this, as described inZac’s answer. Figuring out the right rule by analogy to the many examples in the manual or here on SO should not be hard. | I have a website done in Wordpress and I need to make some changes in the fiendly URLs.I’ve created a page from the admin panel nameddetail, this page reads the template filedetail.phpfrom the templates folder.The URL that is currently mounted ishttp://www.domain.com/detail/1234/and I need that it could be accessed ashttp://www.domain.com/anything/1234/.The following lines have been generated by Wordpress but I don’t understand them and I don’t know how to modify them for my purpose:<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule> | Modify friendly URLs generated by default in Wordpress (via .htaccess) |
Put this code in yourDOCUMENT_ROOT/.htaccessfile:RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^vote([0-9]+)/?$ /vote.php?vote=$1 [NC,QSA,L] | I need help with my .htaccess file. So far, nothing seems to work. I have made a PHP file called vote.php that uses GET variables to redirect the user to the appropriate voting website. Now, I want the user to be able to type myurl.com/vote1 which will redirect them to myurl.com/vote.php?vote=1 and so on vor /vote2, /vote3, /vote4 and /vote5
All help is appreciated!
Thanks,
Tanner | Using .htaccess to redirect /vote to /vote.php?vote=1 |
Place this simple rule in yourDOCUMENT_ROOT/.htaccessfile:RewriteEngine On
RewriteRule ^(literature)/?$ /$.html [NC,L]Reference:Apache mod_rewrite IntroductionThis will internally loadhttp://www.somesite.com/literature.htmlwhen you openhttp://www.somesite.com/literaturein your browser. | Is it possible to remove or hide the .html for a single URL without doing a 301 redirect? All of the examples I have come across involve rewriting all the URLs and some sort of redirect.I would like to rewrite the following URL:http://www.somesite.com/literature.htmltohttp://www.somesite.com/literatureAll of the other URLs should be unaffected and render the .html | Remove HTML extension for specific URL without Redirect |
I suspect 2 things:You don't have mod_proxy enabled on local UbuntuYou may not have anything running on port # 1337 | I am trying to catch a routesome_pathon my website and redirect it to a different port on the same server. The following code works on the server, but not on my localhost box. I'm using Ubuntu<IfModule mod_rewrite.c>
Options +FollowSymLinks -Indexes
RewriteEngine on
RewriteBase /
# Works on the server
RewriteRule ^some_path/(.*)$ http://remoteserver.com:1337/$1 [P,L]
# Does not work on the localhost
RewriteRule ^some_local_path/(.*)$ http://localhost:1337/$1 [P,L]
</IfModule> | .htaccess rewrite for for localhost port mapping? |
Enable mod_rewrite and .htaccess throughhttpd.confand then put this code in your.htaccessunderDOCUMENT_ROOTdirectory:Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteRule ^portfolio/(.*)$ /$1 [L,R=301,NC] | I need to make redirections from a sub-directory to the parent directory.In other words I have to redirect anything matchinghttp://exemple.com/portfolio/product1to :http://exemple.com/product1Is there any way to do that with URL REWRITE ?Thanks | How to redirect url to parent directory with url rewriting |
That code appears to be from one of my answers :)Replace your code with this:Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]
## hide .php extension snippet
# To externally redirect /dir/foo.php?id=123 to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\?id=([^&\s]+) [NC]
RewriteRule ^ %1/%2? [R,L]
# To internally forward /dir/foo/12 to /dir/foo.php?id=12
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/([^/]+)/?$ $1.php?id=$2 [L,QSA]
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\s [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*?)/?$ $1.php [L] | I have a problem with redirect URL in .htaccess. I want to remove .php & question marks from the URL.For Example:www.example.com/test.php?id=12towww.example.com/test/12need like this format.I tried using this code in my .htaccessOptions +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]
## hide .php extension snippet
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]This code just removes the .php extension from the URL. Also need to remove the question mark. | I want to remove question mark & .php extension from the url using .htaccess |
Depending on your URL layout I would go with something like this:RewriteCond %{REQUEST_URI} ^/(A) [OR,NC]
RewriteCond %{REQUEST_URI} ^/(B) [OR,NC]
RewriteCond %{REQUEST_URI} ^/(C) [OR,NC]
RewriteCond %{REQUEST_URI} ^/(E)
RewriteRule ^.*$ /d#%1 [L]Of course you can also do it in one line:RewriteCond %{REQUEST_URI} ^/(A|B|C|E) [NC]
RewriteRule ^.*$ /d#%1 [L] | Using the .htaccess file, how can I loadpage Bwhenpage Ais loaded? I do not want the URL to change, it should still saypage A.example: user loadswww.mysite.com/contactand gets the results ofwww.mysite.com/contact-usPreferably, how can i redirect multiple URLs to the same place? Such as.com/A,.com/B, and.com/Call load the content of.com/d. Is there a way to group many of those together (as opposed to this solution:htaccess redirect without changing url) | htaccess load page B instead of page A without redirecting |
The following seemed to fix my problem:RewriteCond %{ENV:HTTPS} !on [NC] | I have taken over a website and am trying to force https. I have added the following to my .htaccess file:RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L]The rest of the file looks like this:RewriteCond %{REQUEST_FILENAME} !^(.*)/audio_recording/(.*)$
RewriteCond %{REQUEST_FILENAME} !^(.*)/bwcheck/(.*)$
RewriteCond %{REQUEST_FILENAME} !^(.+)/page\.php$
... lots of Conditions
RewriteRule ^(.*)\.* page.php?$1 [L]
IndexIgnore *When I add the https redirect I am getting the following error:The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.and chrome:This webpage has a redirect loop...The url is updated to https however.EDIT:Here is the begining of the .htaccess file:php_value memory_limit 64M
<Files .htaccess>
order allow,deny
deny from all
</Files>
DirectoryIndex index
Options +FollowSymlinks
RewriteEngine on
RewriteBase /
ErrorDocument 404 /web/content/content/404.php | htaccess - The page isn't redirecting properly |
Okay since you cannot upgrade your Apache to latest versions here is onework-around wayto get this conditional setting in place.1 - In theDOCUMENT_ROOTRun this command to create a symbolic link ofindex.phpas__anything.phpln -s index.php __anything.php2 - Put the new code inDOCUMENT_ROOT/.htaccessjust belowRewriteEngine Online. You overall.htaccesswould look like this:# forward all URLs starting with /admin/ to __anything.php
RewriteRule ^(admin(?:/.*|))$ __anything.php?/$1 [L,NC]
# set max_input_vars to 2000 for file __anything.php
<FilesMatch "^__anything\.php">
php_value max_input_vars 20000
</FilesMatch>
# your regular Codeignitor controller code
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]PS:I don't have CI installed so I cannot really test this with CI but otherwise I tested this and got enhancedmax_input_varsvalue. | I want to set aphp_valueflag only for a specific url (rewrited) path. I'm using htaccess to accomplish this. The framework I'm using is CodeIgniter, so there is one htaccess file and url routes are handled by php.Only the backend of the website should havephp_value max_input_vars 3000. The url ishttp://www.example.com/admin/dashboardI was thinking about this in htaccess file:<Location /website.com/admin>
php_value max_input_vars 20000
</Location> | Set htaccess php_value for url rewrited path only |
You could do it explicitly:Options +FollowSymLinks
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^sitemap.xml$ sitemap.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?filename=$1 [L,QSA]
</IfModule>You'll likely run into problems doing this though... You should create exclusions for spiders so they still receive the sitemap.xml | below is my current .htaccess file. I would like to add another condition/rule where if a request for sitemap.xml is made, sitemap.php is served instead. Please help : )Options +FollowSymLinks
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?filename=$1 [L,QSA]
</IfModule> | .htaccess URL re-write (sitemap.xml to sitemap.php) |
$username = 'login';
$password = 'pass';
//...
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($handle, CURLOPT_USERPWD, $username . ":" . $password);
curl_exec($handle); | I want to protect my domain with a password because I just use it to test scripts, but I need to allow curl HTTP POST request. Is this possible?current .htaccess:#AuthUserFile /home/domain/.htpasswds/.htpasswd
#AuthType Basic
#AuthName "Protected Domain"
#Require valid-userPHP curl request$handle = curl_init('http://wwww.domain.com/cgi/mailScript.php');
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS, $serial);
curl_exec($handle);PHP error:Authorization Required
This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.
Additionally, a 401 Authorization Required error was encountered while trying to use an ErrorDocument to handle the request.Edit: I'm not concerned about security as much as just preventing people from exploring the site. | .htaccess password auth but allow post request |
You mean?RewriteEngine On
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /(index\.php)?\?id=([0-9]+)([^\ ]*)
RewriteRule ^ /%3?%4 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/?$ /?id=$1 [L,QSA] | I'm looking to create a URL Shortener, although I'm encountering an issue which I cannot think through.
I need the user to be able to find his id with a get request using a slash(/) instead of a?=for example,Instead of usingoli.pw?id=100I would need it to beoli.pw/100.I looked into URL rewriting but I honestly have no idea how to accomplish this with all get requests.If this is not detailed enough leave a comment below. Thanks! | URL Shortener PHP |
You can do that with a simple rule:RewriteEngine On
RewriteRule ^.*?/(.*)$ /$1 [L,R=301] | url:http://www.side.com/en/page-1/I need to redirect tohttp://www.side.com/page-1/How to do this using .htaccess file, maybe call php file and parse string( URI )? | .htaccess Remove one of GET values and redirect |
Your rewrite base should be/fat-silex/web<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /fat-silex/web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>I've tested it on my localhost, and it works fine | Just getting started with Silex and having some issues.Downloaded thefat zip file, unzipped it intowamp'swwwfolder. So, here'sC:\wamp\www\fat-silex\web\index.php:<?php
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/hello', function() {
return 'Hello!';
});
$app->run();Problem is I'm getting Apache's 404's forhttp://localhost/fat-silex/web/hello, and also for any URL exceptlocalhost/fat-silex/web, where I'm getting Silex'es 404 (as expected). I guess the requests go directly to Apache, and are not routed by Silex. This looks like the problem could be solved with a.htaccessfile, so I added this one, suggested in theofficial documentation:<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /fat-silex
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>However, it doesn't seem to haveanyeffect at all. | Why am I getting these Silex 404's? |
Probably do the trick:<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>UPDATE 1At this part of code:RewriteRule ^index\.php$ - [L][L]Stop the rewriting process immediately and don't apply any more rules. So,RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.php [NC,L]Are not interpreted.UPDATE 2:The server will follow symbolic links:Options +FollowSymLinksThe server will disable multi views:Options -MultiViewsRewrite engine will be enabled:RewriteEngine OnBase directory for rewrite will be/:RewriteBase /If request match a not existing file, continue:RewriteCond %{REQUEST_FILENAME} !-fIf request match a not existing directory, continue:RewriteCond %{REQUEST_FILENAME} !-dRewrite toindex.php, in a not sensitive case, and stop execution of next rules:RewriteRule index.php [NC,L]So, try the follow:Options +FollowSymLinks
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule index.php [NC,L] | UPDATE: Problem solvedAfter many hours, I finally understood that the problem were in folder permission (757 instead of 755).Damn, I feel like a idiot, but at least, problem solved :)Thanks everyone!I'm having a weird problem with my .htaccess and mod_rewrite.Currently, I've the following .htaccess on my root:Options +FollowSymLinks
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.php [NC,L]The problem is:I want to be able to access any existing file.i.e.:mysite.com/anydir/myfile.png -> open the anydir/myfile.png- mysite.com/anydir/script.php -> open anydir/script.php- mysite.com/file.png -> open file.png- mysite.com/notadir/imnotafile -> rewriteBut, everything works except the second point. I've afile.phpin mytestfolder, but when I domysite.com/test/file.php, it keep rewriting it, and it shouldn't...What I'm I doing wrong? | htaccess RewriteCond !-f issues |
You can extend the regular expression forHTTP_HOSTRewriteCond %{HTTP_HOST} ^(?:www\.)?domainY\.com$
RewriteRule .* http://domainX.com/some/path [L]This is a rewrite. If you want to redirect the client, you must add anRflagRewriteRule .* http://domainX.com/some/path [R,L]When everything works as it should, you may replaceRwithR=301.Nevertest withR=301. | I have a site with two domains. I want that whenever domain X is visited (no matter what the path is... /foo/bar/, root or whatever), the browser should redirect to a specific URL.So:domainX.com -> domainX.com
domainY.com -> domainX.com/some/pathThe following kinda sorta works, but it only matches againstdomainY.com, sowww.domainY.comordomainY.com/some/pathdoesn't work.RewriteCond %{HTTP_HOST} ^domainY\.com
RewriteRule ^(.*)$ http://domainX\.com/some/path [L]It has to accept both with and without www before though. Any ideas? | mod_rewrite Redirect to specific URL if domain X is used? |
Since Apache 2.4 you can use this expression in your .htaccess files:<If "%{HTTP_HOST} == 'example.com'">
AddHandler application/x-httpd-php53 .php
</If>https://httpd.apache.org/docs/2.4/expr.html#examplesNote that this does not work in Apache 2.2. | I'm hosting my staging and production servers at Site5, a relatively good hoster IMO. The question is not about their quality but more about an issue related to PHP's version.Our development server is using PHP 5.3 which is a good version, 5.4 being too new, we don't want to use it's features yet, not enough widespread.Problem is, Site5 uses PHP 5.2 by default but you can change to 5.3 using an HTACCESS AddHandler statement. Works fine on Site5 but our dev server crashes when we keep that statement in the HTAccess file.If you use SVN/Git to deploy your web apps, you know that you always keep the same files everywhere, so thats where it hurts, i can't seem to find anything about conditional statements for HTACCESS files for AddHandler. I can write conditions on the rewrite engine easily, but i can't find anything that would look and act like this:#<If SERVERNAME == "targethost.com">
# PHP 5.3 configuration for site5
# AddHandler application/x-httpd-php53 .php
#</If>Anyone has a solution? | Apache HtAccess AddHandler Conditional on servername or ip |
You are matching your referer against^https://(.+\.)*mydomain\.com. Which means if some completely other site, sayhttp://stealing_your_images.com/links to something onprotect.mydomain.com, the first condition will fail, thus the request is never redirected tohttps://unprotected.mydomain.com/. You want to approach it from the other direction, only allow certain referers to pass through, then redirect everything else:RewriteEngine On
RewriteBase /
# allow these referers to passthrough
RewriteCond %{HTTP_REFERER} ^https://(protect|unprotected)\.mydomain\.com
RewriteRule ^ - [L]
# redirect everything else
RewriteRule ^ https://unprotected.mydomain.com/ [R,L] | I'm trying to set up a htaccess file that would accomplish the following:Only allow my website to be viewed if the viewing user is coming from a specific domain (link)So, for instance. I have a domain called. protect.mydomain.com . I only want people coming from a link on unprotected.mydomain.com to be able to access protect.mydomain.com.The big outstanding issue I have is that if you get to protect.mydomain.com from unprotected.mydomain.com and click on a link in the protect.mydomain.com that goes to another page under protect.mydomain.com then I get sent back to my redirect because the http_referer is protect.mydomain.com . So to combat that I put in a check to allow the referrer to be protect.mydomain.com as well. It's not working and access is allowed from everywhere. Here is my htaccess file. (All this is under https)RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_REFERER} ^https://(.+\.)*mydomain\.com
RewriteCond %1 !^(protect|unprotected)\.$
RewriteRule ^.*$ https://unprotected.mydomain.com/ [R=301,L] | htaccess only accept traffic from specific http_referer |
Use this rule :RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.html$ $1.php [L]It will redirect any request to a html file (that does not exists phisicaly) to a php file. | I want to change the extension of php file.For example the file home.php is called in browser it should be shows like home.html.
I can done it in codeigniter by usingsuffixvariable in config file.But how can i achieve it in core php? I think it can be done through .htaccess file or may be from other way but how to do?please let me know.i try:RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.htmlby using above code i try to but it is was not changed? or if there any other way to do it please let me know. | How Do I change extension of php file |
You could try using mod_alias'RedirectMatchto force something in the URI for the redirect. In the htaccess file in site.com's document root, add:RedirectMatch 301 ^/(.+)$ http://www.newsite.com/$1This will make it so anything afterhttp://www.site.com/will get redirected, but justhttp://www.site.com/will not. However,http://www.site.com/index.htmlwillget redirected. If that's an issue, you can use mod_rewrite:RewriteEngine On
RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_URI} !^/index.html$
# and whatever else you don't want redirected
RewriteRule ^(.*)$ http://www.newsite.com/$1 [L,R=301] | i need a help witch an htaccess 301 redirect.I have a site www.site.com but i need to change all pages to www.newsite.com but i want not move www.site.com (for a pages information)EXAMPLE:www.site.com (not move) index of to put then a template or message
www.site.com/2012/08/page.html move to www.newsite.com/2012/08/page.html
www.site.com/tag/keyword/ move to www.newsite.com/tag/keyword/
www.site.com/category/general/ move to www.newite.com/category/general/how i can do that? Thanks | htaccess how to redirect all pages, but not the root directory |
You can list all files in a specific directory usingglob().//here, I will grab all PHP file names, and throw them into a assoc array:
$fileArr = glob('path/*.php');
foreach($fileArr as $val)
{
echo $val."<br>";
}
//now you have all your file names listedTo prevent users makinghttprequests to them, you usehtaccess:Make a .htaccessfile in the directory your files are sitting in and paste this into it:deny from allNow, no one can makehttprequests to files in that directory.Why you want to do this though, is anyone's guess. | In my server I want to show the list of the php files available in a folder. But I don't want to let my users to copy or save them, just be able to open the PHP file. | disable downloading of the PHP files |
Try encoded URL instead:/xyz/h%C3%A4ndedruck.htmlTo get this string in PHP you can use theurlencodefunction.There are also many websites that can do urlencoding for you. For example:http://meyerweb.com/eric/tools/dencoder/ | The following htaccess rule doesn't work because of the umlauts.Redirect 301 /xyz/händedruck.html /new/händedruck.htmlHow can this redirect be modified so that it works? | Umlauts in htaccess redirects |
.htaccess something like:RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) /url_rewrite.php?path=$1 [L,QSA]database table something like:+------+--------+
| path | url |
+------+--------+With the path as the PRIMARY KEY.And a PHP script calledurl_rewrite.phpthat takes the path parameter from the URL, does a lookup on the database to find the real url and performs an HTTP 301 redirect.The url_rewite.php page might look something like this (this is pretty much boilerplate code and will need adjusting to fit your requirements - realistically we shouldn't be using mysql_query() any more either - PDO or MySQLi are better and aren't well, deprecated).<?php
// -- database connection and any intialisation stuff you may have might go here ...
//get the path
$sPath = !empty($_GET['path']);
// -> error trapping for empty paths here
//retrieve the "real" url from the database
$dbQry = mysql_query("SELECT `url` FROM `seourls` WHERE `path` = '" . mysql_real_escape_string($sPath) . "' LIMIT 0, 1");
// -> error trapping here for query errors here
$dbResponse = mysql_fetch_row($dbQuery);
// -> error trapping here for empty recordsets here
$sRealPath = $dbResponse[0]; # which might be "/articles_en.php?artid=89"
//redirect
header("HTTP/1.1 302 Found");
header("Status: 302 Found"); # for Chrome/FastCGI implementation
header("Location: {$sRealPath}");
die();
?> | I have php application which have to be partially rewritten because of the customer request to have SEO frendly urls.My links are as follow:www.mysite.com/articles_en.php?artid=89, where I will have to change the url in this:www.mysite.com/articleTitleThen I have this url:www.mysite.com/halls.php?fairid=65 which should becomewww.mysite.com/fairnameAnd www.mysite.com/companies.php?fairid=65&hallid=23 which should becomewww.mysite.com/fairname/hallnameYou get the idea.I need a help with the approach. Is it good idea in the tables of the fairs, halls and articles to create a field in the table named for example alias and then to attempt to rewrite the url? Anyone can help me with the steps how to create this script, or to point me to better approach?I am good at php, but not good at all with regular expressions, so I will be lost on the .htaccess part.Any help will be deeply appreciated.Regards, Zoran | rewriting php application to get seo friendly url's |
You just need to add a%1RewriteCond %{HTTP_HOST} ^(.*)oldomain.org [NC]
RewriteRule ^(.*)$ http://%1newdomain.com/$1 [R=301,L] | I am moving a site from an old domain with several subdomains to a new domain. I'd like to create a rewrite rule that will just swap out the old domain for the new one, but I am not savvy enough with regular expressions & .htaccess to do this :PI can get the 301 redirect working for the pages on the domain:RewriteCond %{HTTP_HOST} ^(.*)oldomain.org [NC]
RewriteRule ^(.*)$ http://newdomain.com/$1 [R=301,L]Any clues on how to modify this to include the subdomain as well? Or am I stuck listing all the subdomains in separate rewrites? | .htaccess rewrite rule to keep subdomains when redirecting to new domain |
If you are usingphp_flagthen you are probably using mod_php5. Custom 'php.ini' files aren't supported with this. You would need to use suPHP or equiv as thephp.iniis only loaded at PHP startup, and this isn'tper-requestfor mod_php5 and FCGI.However, since you are using PHP 5.3 you can also use.user.ini fileswhich are parsed on a per-request basis. | I'm running Apache 2.26, on Windows 7 with PHP 5.39 mod_ssl/2.2.6 OpenSSL/0.9.8g .PHP works fine, so does Apache.However, I want to try and create custom php.ini files per directory, for my test sites.I could - and did - use php_flag but would like to try to create a custom php.ini file that works. I tried to Google this, but couldn't find anything relevant.This is my current .htaccess for C:/www/vhosts/localhost/testsite1:RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
#RewriteCond %{REQUEST_fileNAME} !\.php -f
#RewriteRule .* index.php
AddType text/html .asp
AddHandler application/x-httpd-php .page
php_value include_path "./php:/php/"Yet, I made a change in the custom php.ini within the php to have short tags off [for testing only] but it didn't pick it up, the php code showed instead.Any help is appreciated with this; it'll be extremely useful!(bear in mind, this Apache install is a development/testing one) | Custom php.ini per-directory (for testing sites) |
It sounds like he doesn't allow you to override safe mode. Which makes sense because what would be the point in running a shared server in safe mode if anyone could disable it as they saw fit. You're probably going to need to relocate to a server without safe mode as the only options for changing that value are not going to work for you. Safe mode is already deprecated and is not meant to be used. The "safe" way for a server owner to handle security is through the OS and setting up correct account permissions. | I'm on a server with safe mode on.
Now the server allows .htaccess files.
I have one in my public_html folder with settings of Wordpress.
Now in a sub-domain i want to insert an.htaccessfile that dsiables safe mode.i Tried theese:php_value safe_mode 0
php_flag safe_mode 0
php_value safe_mode off
php_flag safe_mode offbut none worked.Anyone knows how can i do that?
I Can not ask the server owner to disable safe mode, and basicly can't ask him anything. | Setting safe mode to OFF in .htaccess file does not work |
Something like this should fit you needs:RewriteEngine On
RewriteBase /
RewriteRule (.*)\.html$ / [QSA,R=301,NC,L] | I'm helping a client migrate an old site which used .html extension at the end of the web address to a properly named URL structure. I want to do a redirect for all URLs that end in .html to the homepage.I tried this but it didn't work:RewriteRule ^(.*)\.html$ $1http://domain.org [NC] | .htaccess redirect traffic hitting .html links to TLD homepage |
It does in fact depend on thePHP SAPI. This precise.htaccesssyntax will only work withmod_phpsetups, not withCGIorFastCGIinstallations. In the latter case you would use a.user.ini(for PHP 5.3 onwards) instead.Most of the options you have there can however be configured at runtime. Useini_set()atop the invocation script:ini_set("display_errors", 0);Note that for_startup_errorsit's obviously too late to be configured there. Also it's redundant to disablehtml_errorsand the docref things ifdisplay_errorsis already off. | I've been reading a couple of articles on website security and they recommend adding this code to your.htaccessfile to prevent the display of PHP errors:# supress php errors
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0If I add this codedirectlyinto my.htaccessfile I am given a 500 internal server error. What's wrong with it? Is this all deprecated stuff? | PHP error handling with .htaccess |
To make the new rewrite rule work with "one entry point rewriting", have yourrewriteRuleslike this:TheQSAflag ismandatoryas you are adding a new query string.RewriteEngine On
RewriteRule ^(post)/([\w\d\-]+)/?$ $1/main?title=$2 [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . index.php [L]FlagQSAApache Docs.!-lchecks that the requested URI is not a symbolic ink. | I have some URLs like these:http://plutov.by/post/cubique_zf_jqueryhttp://plutov.by/post/mysql_useful_queriesHow can I with help of Apache mod_rewrite open the next pages?http://plutov.by/post/main?title=cubique_zf_jqueryhttp://plutov.by/post/main?title=mysql_useful_queriesAlso, will be this new rewrite rule work with "one entry point rewriting"?RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]Thanks. | htaccess mod_rewrite part of url to GET variable |
You should move your new rule atop the RewriteCond block:RewriteRule ^/?ajaxDispatcher.php$ - [L]Otherwise the RewriteConditions don't cover the extensions RewriteRule anymore, for which I assume they are intended.Another alternative is turning it into another RewriteCond of course:RewriteCond %{SCRIPT_NAME} !ajaxDispatcherOr injecting it as assertion into the final RewriteRule(?!ajaxDispatcher.php).The ordering thing is best explained on Serverfault:https://serverfault.com/questions/214512/everything-you-ever-wanted-to-know-about-mod-rewrite-rules-but-were-afraid-to-as | I have an htaccess rewrite setup in my PHP application to route files via the bootstrapper file. In essence, the goal is to take a URL such as www.domain.com/view/key/value/key/value where the view would route accordingly and the key/value pairs would be available via a function I wrote in the bootstrapper to the views. All was working well...That is, until I started doing ajax-y stuff. I'm routing all my ajax queries through a single file, ajaxDispatcher.php. When I did that, the htaccess (correctly) caught the request and used my bootstrapper to route it inappropriately. Similarly, it was attempting to route unwanted files such as .ico, .css, etc.I figured out the file extension routing exception, however, I've not been able to have .htaccess ignore rewrite rules for the single file ajaxDispatcher.php. Here's where my code stands:RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/ajaxDispatcher.php$ $0 [L]
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php?route=$1 [L]How do I get .htaccess to ignore the routing rules only for ajaxDispatcher? | Excluding files from htaccess rewrite rules |
RewriteCond directives only apply to the rule directly following them.Try the follwingRewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ /index.php?type=cat&id=$1 [QSA,L]
RewriteCond %{REQUEST_URI} !\.(css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^page/([^/]+)$ /index.php?type=page&name=$1 [L]
#rewrite requests for page/images to images
RewriteCond %{REQUEST_URI} ^/page(/images/.+)$ [NC]
RewriteRule . %1 [L]EDIT.
Modified to rewrite page/images to images | I have the following in my .htaccess which is :RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ /index.php?type=cat&id=$1 [QSA,L]
RewriteRule ^page/([^/]+)$ /index.php?type=page&name=$1This seems to work just fine but relative paths to pictures and css files inside of index.php become broken in the second case (Page). did not work. In second case, all images are pointing to page/images/ instead of image/Other than hardcoding the actual path to images, is there any other way to fix this?images, css, js folders are located in the root. This is how the root looks like.htaccess
index.php
images/
css/
js/ | .htaccess clean URL and relative paths |
There isn't a way to disable inheritance, sadly. An easier way could be to create a single folder in your web root for "everything else", and in the .htaccess in there, put theRewriteEngine offstatement.I think you can do something withRewriteCondto disable this. If you want all subfolders to just be accessible (and rewrite anything that doesn't match an existing subfolder), you can useRewriteCond !-d. | AFAIK by default all .htaccess files in all directories leading to the file requested are parsed, i.e. in this setup:DOC_ROOT = /usr/local/www/dataAllowOverrideis set toAllin the above directoryif a file at/dir1/dir2/dir3/fileis requested, all folders from/down are being checked for.htaccess. If the file is found it is parsed and then the execution is continued based on combined contents of the.htaccessfiles.So here's my setup:DOC_ROOT = /usr/local/www/data- that's where all static and php files are kept.there's a.htaccessin theDOC_ROOTthat rewrites all but some requests to index.php.there's a/Python/root.wsgiin theDOC_ROOTand in httpd.conf there's this:WSGIScriptAlias /apps /usr/local/www/data/Python/root.wsgiAs you can imagine I do not want .htaccess to be used at all for the /Python folder, but it is. How do I prevent it?I tried setting this in httpd.conf, but it doesn't do the job:<Directory "/usr/local/www/apache22/data/Python">
AllowOverride None
</Directory>If I do put .htaccess in the Python folder withRewriteEngine offthat seem to do the job, but I don't want to be forced to put such a file in each of the subfolders I don't want to root .htaccess to be used. | How to prevent .htaccess inheritance? |
If you've gotmod_expiresinstalled on your apache server you can put something like this in your.htaccessfile. This example is PHP orientated (actually grabbed from the Drupal 7.htaccessfile) but should serve as a good starting point.FileETag MTime Size
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
<FilesMatch \.php$>
# Do not allow PHP scripts to be cached unless they explicitly send cache
# headers themselves. Otherwise all scripts would have to overwrite the
# headers set by mod_expires if they want another caching behavior.
ExpiresActive Off
</FilesMatch>
</IfModule> | Was wondering is this possible in .htaccess?I'm currently caching .js, .css and all image files via PHP (and providing the cached only if the file has not been modified by checking the filemtime()).However someone suggested it's possible via .htaccess and much faster, so was hoping maybe someone can shed some light...I've looked around and found various snippets but none which cover what I'm after. | .htaccess cache static content (unless modified)? |
if you want temprorary redirect use:RewriteRule ^garrett\-([a-z0-9\-]+)/?$ /garrett-metal-detectors/garrett-$1/ [R=302,L]if you want permanent redirect use:RewriteRule ^garrett\-([a-z0-9\-]+)/?$ /garrett-metal-detectors/garrett-$1/ [R=301,L] | Hi I'm not a programmer by any stretch of the imagination and am trying to do a multi 301 redirect in my htaccess file based on the following:So I have a ton of urls all with similar naming conventions - here is a sample of 2.http://www.hollandsbrook.com/garrett-at-gold/
http://www.hollandsbrook.com/garrett-ace-250/These urls need to redirect to:http://www.hollandsbrook.com/garrett-metal-detectors/garrett-at-gold/
http://www.hollandsbrook.com/garrett-metal-detectors/garrett-ace-250/I could just redirect them 1 line at a time, but I'd like to use regex.Here's what I was thinking so far but not working:RewriteRule ^garrett-([a-z])/$ /garrett-metal-detectors/$1/ [R]Basically i need to redirect any page right off the root that starts with "garrett-" to include the folder path of "garrett-metal-detectors".Any thoughts would be MUCH appreciated. Many thanks in advance for your help. | .htaccess Redirect sub-folder |
Based on your comment (from level-3 to level-2 folder EXACTLY with 301 Permanent Redirect):RewriteEngine On
RewriteBase /
RewriteRule ^([^/]+/[^/]+/)[^/]+/$ http://www.example.com/$1 [QSA,R=301,L]This rule will redirectexample.com/hello/pink/kitten/toexample.com/hello/pink/If URL structure is different, then NO redirect will occur:missing trailing slash (e.g.example.com/hello/pink/kitten)4-level deep URL (e.g.example.com/hello/pink/kitten/family/)This rule needs to be placed in.htaccessin website root folder. If placed elsewhere (e.g. Apache config file, inside<VirtualHost>, for example) the rule needs small tweaking. | http://mysite.com/level-1/level-2/level-3/I want to redirect tohttp://mysite.com/level-1/level-2/"level-1" and "level-2" can be anything the user enters... (not these exact words)Could you direct me to a tutorial or give me a few pointers?Thanks a lot!! | htaccess redirect rules - How to redirect up one level? |
Try this:RewriteEngine on
RewriteRule 80X80-(.*)$ https://www.othersite.nl/imgs/prd/kln/$1
RewriteRule 150x150-(.*)$ https://www.othersite.nl/imgs/prd/std/$1 | I want to redirect all my product images to an external site using htaccess.
However I cant figure out how to use dynamic variables, the image-url looks like this:httpz://localhost/oc1505/image/80x80-10035.jpgWhere 80x80 is the height and the width, and the 10035.jpg is the link to the external image.
So in this case I would like to redirect it to an url that looks like:httpz://www.othersite.nl/imgs/prd/kln/10035.jpghow ever if the source image is 150x150-10035.jpg it should redirect to.httpz://www.othersite.nl/imgs/prd/std/10035.jpgAnd I have a few other formats that I would like to redirect.If someone could help me out a little I would be very happy. | .htaccess dynamic imageurl rewrite |
Yes you can access forrm POST variables in a page of Wordpress.I created a page template like this:<?php
/*
Template Name: Page with Form
*/
?>
<?php get_header(); ?>
<div id="content" class="widecolumn">
<?php
var_dump($_POST);
if (have_posts()) : while (have_posts()) : the_post();?>
<div class="post">
<h2 id="post-<?php the_ID(); ?>"><?php the_title();?></h2>
<div class="entrytext">
<?php the_content('<p class="serif">Read the rest of this page »</p>');?>
</div>
</div>
<?php endwhile; endif; ?>
<?php edit_post_link('Edit this entry.', '<p>', '</p>'); ?>
</div>
<form id="test" method="post">
<input id="srchbox" name="term" size="28" value="" type="text">
<input name="submit" value="Submit" align="absmiddle" type="submit">
</form>
<?php get_footer(); ?>Then I created a page through Wordpress admin panel and used above page template.You can see I have a sample form "test" in this page template. Now when I visited the newly created page in my browser and entered some text in form and submitted the form I got this forvar_dump($_POST);line:array(2) {
["term"]=>string(7) "foo-bar"
["submit"]=>string(6) "Submit"
}As you can see Wordpress doesn't interrupt anything and your page has full access to your$_POSTarray for Form POST variables. | I built a contact form in PHP inside a Wordpress page, using the exec-php plugin to val and run the code. However, the Wordpress rewrite system seems to override the POSTed form data being sent to the page. Is there any way to ensure that this data gets passed through? All I have in my ,htaccess is the standard WP rewrite block. | Can you access POST variables from within a Wordpress page? |
If you want the subdirectory to require the same password as the parent directory, you don't need the.htaccessat all in the subdirectory.Or are you trying to use adifferentpassword in the subdirectory?[Update:]In which case, you need to limit the parent'srequireto not include the subdirectory in question — through aFilesMatchdirective, for instance. Keep your subdirectory's .htaccess the same, and modify the parent's to include something like:<FilesMatch "\.(private|dirs|are|listed|here)">
require valid-user
</FilesMatch>(It seems that there's no way to negate a FilesMatch regex; but I might be wrong about that.) | Order Deny,Allow
AuthUserFile /var/www/subdirectory/.htpasswd
AuthName "Authorization Required"
AuthType Basic
require valid-user^my .htaccess file.However, the parent directory has a password.I want this directory to ask only for one password (even though it asks for the second password, the second password can be left blank. Despite this, i want to remove the second password because it is annoying). | How to use a different password in a subdirectory (.htaccess) |
You can use HTTP_HOST instead of REQUEST_HOST. To make different favicon.ico for 2 different alias, you can try below configuration to make to work...RewriteCond %{HTTP_HOST} ^myhost.com$
RewriteRule ^favicon\.ico$ /images/favicon1.ico
RewriteCond %{HTTP_HOST} ^mynewhost.com$
RewriteRule ^favicon\.ico$ /images/favicon2.icothis way you can make it work... i tried on my domain and it works... :) | I have 2 server alias poiting to the same folder and using the same .htaccess, what I want to do is to use different favicons for each server alias.I tried withRewriteCond %{REQUEST_HOST} ^myhost.com$
RewriteRule ^favicon\.ico$ /images/favicon1.icoBut i'm still not able to make it workAny answer, tip or solution? | Use a favicon for each host via htaccess |
To answer my own question...I wound up changing the Apache file /etc/apache/sites-available/default from AllowOverRide = None to AllowOverRide = All. | I am attempting to move my Codeigniter projects from a shared hosting service to Amazon EC2 and am running into some challenges with my .htaccess settings. These settings enabled me to not have to include index.php in the url. My previous .htaccess is shown below and worked as expected with my previous hosting provider:<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /simple.com/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>With my Amazon EC2 instance, I now have full access to the LAMP stack and have confirmed that the Apache Mod_Rewrite module is enabled.I have set up my EC2 instance with two Virtual Host directories, one for each of my sites. Both sites serve up their CI applications as expected, but require index.php to be in the url.I've tried inserting my Amazon EC2 public path into the .htaccess file as follows but still no luck:RewriteBase /ec2-55-27-191-14.compute-1.amazonaws.com/simple/I am sure this is 100% user error on my part and would greatly appreciate your diagnosis! | Moving Codeigniter Project to Amazon EC2, htaccess and ModRewrite Problems |
Just doing a sweep of old suphp Qs.mod_suphpuses the standard parameter parser so in principle %{DOCUMENT_ROOT} should work. The issue that you almost certainly have is that suPHP is generally used for shared hosting solutions and for these, the users effective DOCUMENT_ROOT is not the same as that established by the DocumentRoot directive in the system config.Most vendors set up an environment variable to point at the users document root. My host sets up DOCUMENT_ROOT_REAL, another that I've come across is PHP_DOCUMENT_ROOT. You need to look at your phpinfo() report to see what applies in your case. So on my .htaccess, I usesuPHP_ConfigPath %{ENV:DOCUMENT_ROOT_REAL}/_privateand that works fine for me. | My server uses suPHP and so each website has it's own php.ini file. My host recommended adding the following in my .htaccess file:<IfModule mod_suphp.c>
suPHP_ConfigPath /home/user/public_html
</IfModule>This basically points to the site's php.ini file. However, I am trying to have a standard .htaccess file across all sites that I don't need to edit- basically part of my "boilerplate" site that I start off with. I tried to change the above to this:<IfModule mod_suphp.c>
suPHP_ConfigPath %{DOCUMENT_ROOT}/public_html
</IfModule>But this doesn't work. As you can tell I am probably not understanding how this all works. Can anyone help me with the above code so that I don't need to put the exact path in for each .htaccess file, and get Apache to work out the path to my php.ini file?I hope that makes sense, it's a little difficult to explain! | php.ini with suPHP in .htaccess |
This could be achived using robots.txt but since you're asking how to throw the 404 page manualy here it is :<?php
if ( preg_match('/thisisnotwanted/i',$_SERVER["REQUEST_URI"]) ) {
header("HTTP/1.0 404 Not Found - Archive Empty");
require TEMPLATEPATH.'/404.php';
exit;
}
get_header();
?>This bit of code is just an example on how you can display a 404 page, and it shouldn't be used in "production", instead use robots.txt as Michiel Pater sugested . | I am managing a wordpress blog and want to throw a 404 error whenever the url contains a string pattern (example: if the url contains "thisisnotwanted"). I was thinking I will be able to add something to the htaccess file like: Redirect "thisisnotwanted" 404Can someone help? I just don't want Google to index pages with this parameter. | Want to throw 404 Errors when URL contains a certain string - Wordpress |
Straight from Apache's documentationThe most common method is Basic, and this is the method implemented by mod_auth_basic. It is important to be aware, however, that Basic authentication sends the password from the client to the serverunencrypted. This method should therefore not be used for highly sensitive data, unless accompanied by mod_ssl. Apache supports one other authentication method: AuthType Digest. This method is implemented by mod_auth_digest and is much more secure. Most recent browsers support Digest authentication.Please read the restHEREPlease read the comments, things have changed since 2011. Good catch @reve_etrange | I need to protect a clients CMS with a username and password, only one username is needed. I was going to use htaccess because its so quick to add.I'll be adding it using the password directories feature in WHM which stores the passwords here:
AuthUserFile "/home/username/.htpasswds/public_html/cms/passwd"How secure is this? Are there ways to get into folders such as .htpasswds? | How secure is htaccess authentication |
Just add the [QSA] flag to your other flags to have the [Q]uery [S]tring [A]ppended automatically.[L,R=301,QSA] | I've correctly configured my website to re-route every piece of traffic frommywonderfulwebsite.com/folder1/whatever-url.phptohttp://folder1.mywonderfulwebsite.com/whatever-url-as-above.phpQuestion is: many times, an external website links the page with GET parameters, for examplemywonderfulwebsite.com/folder1/whatever-url.php*?trackingToken=1*So, question is how to make the mod_rewrite pass in the GET parameters to the "rewrited" url, like this:folder1.mywonderfulwebsite.com/whatever-url-as-above.php*?trackingToken=1*Currently, I'm doing the following:<VirtualHost *>
ServerName mywonderfulwebsite.com
ServerAlias www.mywonderfulwebsite.com
DocumentRoot /var/www/mywonderfulwebsite/
DirectoryIndex index.html
<Directory />
allow from all
Options +FollowSymlinks -Indexes
</Directory>
RewriteEngine On
RewriteRule ^/folder1/(.*)?$ http://folder1.mywonderfulwebsite.com/$1&%{QUERY_STRING} [L,R=301]
</VirtualHost>This piece of htaccess is awful: for example, trying to access this url:www.mywonderfulwebsite.com/folder1/atextfile.txtRedirects tofolder1.mywonderfulwebsite.com/atextfile.txt&In fact, the mod_rewrite appends the trailing &How do I fix this issue?How to correctly redirecting to the correct ( also with GET parameters ) url?Many thanks | Maintaining the query string with mod_rewrite |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.