2013-12-07 6 views
3

Я пытаюсь иметь Nginx перехватывать URL, например:Nginx Laravel 4 URL запроса переписать

http://website.dev/results?livesearch=bill+clinton 

и иметь его показать, как:

http://website.dev/results/bill-clinton 

Я использую Laravel, как мой PHP. Когда я печатаю URL вручную (http://website.dev/results/bill-clinton), я получаю правильную страницу.

То, что я пытаюсь сделать, это ввести тип пользователя в поле ввода текста; как только они нажмут кнопку «Отправить», я бы хотел, чтобы URL-адрес отображался как http://website.dev/results/bill-clinton вместо http://website.dev/results?livesearch=bill+clinton

Я попытался оглянуться по интернету за помощью, но не имел никакого успеха.

Мой виртуальный сервер nginx находится ниже.

server { 

    listen  80; 
    server_name website.dev; 

    access_log logs/host.access.log main; 
    error_log logs/host.error.log; 
    rewrite_log  on; 

    root /path/to/www; 
    index index.php; 

    #error_page 404    /404.html; 
    error_page 500 502 503 504 /50x.html; 

    location = /50x.html { 
     root html; 
    } 

    location/{ 
     # Pretty URLs. Allows removal of "index.php" from the URL. 
     # Useful for frameworks like Laravel or WordPress. 
     try_files $uri $uri/ /index.php?$query_string; 
    } 

    # Added cache headers for images, quick fix for cloudfront. 
    location ~* \.(png|jpg|jpeg|gif)$ { 
     expires 30d; 
     log_not_found off; 
    } 

    # Only 3 hours on CSS/JS to allow me to roll out fixes during 
    # early weeks. 
    location ~* \.(js|css|ico)$ { 
     expires 3h; 
     log_not_found off; 
    } 

    # Turn off logging for favicon and robots.txt 
    location = /robots.txt  { access_log off; log_not_found off; } 
    location = /favicon.ico { access_log off; log_not_found off; } 

    # Removes trailing slashes (prevents SEO duplicate content issues) 
    if (!-d $request_filename) 
    { 
     rewrite ^/(.+)/$ /$1 permanent; 
    } 

    # Removes trailing "index" from all controllers. 
    # Useful for frameworks like Laravel. 
    if ($request_uri ~* index/?$) 
    { 
     rewrite ^/(.*)/index/?$ /$1 permanent; 
    } 

    # Unless the request is for a valid file (image, js, css, etc.), 
    # send it to index.php 
    if (!-e $request_filename) 
    { 
     rewrite ^/(.*)$ /index.php?/$1 last; 
     break; 
    } 

    location ~ \.php$ { 
     include       fastcgi.conf; 
     fastcgi_split_path_info   ^(.+\.php)(/.+)$; 
     fastcgi_pass     127.0.0.1:9000; 
     fastcgi_index     index.php; 
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
    } 

    location ~ /\.ht { 
     deny all; 
    } 
} 

ответ

3

Regex и если = почти всегда плохо в Nginx.

Почти все ваши перезаписи regex в nginx будут серьезно влиять на производительность здесь.

Для вашего первоначального маршрута для симпатичной URL, вы можете использовать это:

location/{ 
     try_files $uri $uri/ /index.php?$query_string; 
} 

Laravel достаточно умен, чтобы посмотреть в $_SERVER["PATH_INFO"]. Он также обрабатывает косые черты.

Маршрутизация

Вы можете затем маршрут поиска вы планируете сделать так:

Route::any("/results/{search?}", "[email protected]"); // ? = optional 

Эта запись [email protected]. Это не статично.

В app/controllers/Search.php, вы должны были бы следующим:

<?php 

class Search extends BaseController { 

    public function results($search = null) { 
     if (!$search) { 
      if (Input::has("q")) { 
       // This is where you'd do SEO cleanup to remove special chars. 
       return Redirect::to("/results/" . Input::get("q")); 
      } 
     } else { 
      // do stuff with the $search variable here 
     } 

    } 

} 

Когда вы переписываете в Nginx, вы на самом деле перенаправить пользователь в любом случае. (через перенаправление 301, 302 или 308).

Вы можете избежать этого дополнительного запроса с помощью javascript (отправьте браузер на адрес /request/search-term on submit), и у вас будет приятный кусок сохраненных запросов, не влияя на опыт людей, которые просматривают с помощью noscript.

+1

необходимо добавить возврат к прямой. Переадресация :: в ("/ results /". Input :: get ("q")); поэтому он будет выглядеть как «return Redirect :: to («/results/». Input :: get (« q »)); –

Смежные вопросы